简体   繁体   中英

SwiftUI - How to align bottom edge to center of sibling

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()
}

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!

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: 结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM