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