Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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! :)

like image 764
ref2111 Avatar asked Apr 15 '20 17:04

ref2111


1 Answers

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

like image 87
Asperi Avatar answered Dec 14 '22 15:12

Asperi