Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - How to align bottom edge to center of sibling

Tags:

ios

swift

swiftui

Please have a look at this image before reading the question

Please have a look at this image before reading the question

I'm currently trying to align the red view's vertical center (/centerY) to the bottom edge of the green view in a SwiftUI View.

I'm coming from UIKit where I would solve this with something like viewA.centerYAnchor.constraint(toEqual: viewB.bottomAnchor)

But how would you solve this the SwiftUI way? I have kind of the following hierachy:

VStack {
    ZStack {
        Image("someImage")
        Text("Awesome Title") // <- align center to the Image's bottom edge
            .frame(width: 200, height: 130)

    }
    Spacer()
}
like image 799
RedX Avatar asked Nov 11 '19 19:11

RedX


2 Answers

I found the solution:

  1. Set the ZStacks alignment to .bottom. Now the red view will be aligned to the green views bottom edge. Thanks to @Andrew. But this is not enough:

  2. Set the red views .alignmentGuide to the following:

    -> .alignmentGuide(.bottom) { d in d[.bottom] / 2 }

Explanation: Now the green view's bottom edge will be aligned to 50% of the red view's height! Awesome!

like image 60
RedX Avatar answered Oct 04 '22 10:10

RedX


If you remove the frame from the text and add a bottom alignment to the ZStack, it will give you the desired effect.

        VStack {
            ZStack (alignment: .bottom) {
                Image("someImage")
                Text("Awesome Title") // <- align center to the Image's bottom edge
            }
            Spacer()
        }

result: result

like image 37
sfung3 Avatar answered Oct 04 '22 08:10

sfung3