I searched stackoverflow, but unfortunately didn't find a solution to this particular case.
I try to display following scenario:
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:
It would be great if somebody could help me code this scenario in SwiftUI! :)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With