Here is a breakdown.
I have a zstack that contains 2 vstacks.
first vstack has a spacer and an image second has a text and button.
ZStack {
VStack {
Spacer()
Image("some image")
}
VStack {
Text("press the button")
Button("ok") {
print("you pressed the button")
}
}
}
Now this setup would easily give me an image on the bottom of a zstack, and a centered title and button.
However if for example the device had a small screen or an ipad rotates to landscape. depending on the image size (which is dynamic). The title and button will overlap the image. instead of the button being "pushed" up.
In UIKit this is as simple as centering the button to superview with a high priority and having greaterThanOrEqualTo image.topAnchor with a required priority.
button would be centered in screen but if the top of the image was too big the center constraint would give priority to the image top anchor required constraint and push the button up.
I have looked into custom alignments and can easily get always above image or always center but am missing some insight in having it both depending on layout. Image size is dynamic so no hardcoded sizes.
What am i missing here? how would you solve this simple yet tricky task.
There might be an easier way using
.alignmentGuidebut I tried to practice onLayoutfor this answer.I created a custom
ImageAndButtonLayoutthat should do what you want: it takes two views assuming the first is the image and the second is the button (or anything else).They are put into subviews just for clarity, you can also put them directly into
ImageAndButtonLayout. For testing you can change the height of the image via slider.The Layout always uses the available full height and pushes the first view (image) to the bottom - so you don't need an extra
Spacer()with the image. The position of the second view (button) is calculated based on the height of the first view and the available height.