'SwiftUI: How to center a view vertically and horizontally inside of a container view and put something under it

I searched stackoverflow, but unfortunately didn't find a solution to this particular case.

I try to display following scenario:

  • a container view
  • a Text that is centered horizontally and vertically in that container view
  • a Text that is below this centered Text

Whatever I try I can't center that Text horizontally and vertically in the container view and put something underneath it, without putting it out of the center of the container view.

For better understanding, I portrayed this behaviour in a storyboard:

enter image description here

It would be great if somebody could help me code this scenario in SwiftUI! :)



Solution 1:[1]

Here is possible approach (at least for start) that I would prefer, because both labels remains independent, and always be centered in parent container by primary text.

demo

struct DemoCenteredText: View {
    var body: some View {
        GeometryReader { gp in
            ZStack {
                Text("Primary Text").font(.title)
                    .alignmentGuide(VerticalAlignment.center, computeValue: { $0[.bottom] })
                    .position(x: gp.size.width / 2, y: gp.size.height / 2)
                Text("Secondary Text")
                    .alignmentGuide(VerticalAlignment.center, computeValue: { $0[.top] - 16 })
            }
        }
    }
}

The .position in above fixes primary title at center of parent container, which free space is consumed by GeometryReader, and alignmentGuide force layout to place secondary text at offset 16 from bottom of primary text (actually in the same way as constraint in your question).

backup

Solution 2:[2]

try this:

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, World! Centereed")
                .overlay(Text("john").offset(y: 30))
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Chris