ios – Align one view horizontally to the middle of the screen in an HStack


I want to have the Text “2” aligned just were the vertical black line is:
enter image description here

I have an HStack with three elements. I want the first element to be on the leading edge, the second element centered, and the third element on the trailing edge.

The code I have tried is this:

VStack(alignment: .middle) {
    HStack {
        Text("1")
        Spacer()
        Text("2")
            .alignmentGuide(.middle) { d in
                d[VerticalAlignment.center]
            }
        Spacer()
        Text("Some more text")
    }
    .background(.red)
    .padding()
}
.frame(maxWidth: .infinity)
.background(.blue)

And the custom HorizontalAlignment I use is this:

extension HorizontalAlignment {
    enum Middle: AlignmentID {
        static func defaultValue(in context: ViewDimensions) -> CGFloat {
            context[HorizontalAlignment.center]
        }
    }

    static let middle = HorizontalAlignment(Middle.self)
}

However, this does not create the desired alignment effect.

How could I have the text “2” centered in the middle of the screen while the other views are leading and trailing?

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img