So basically I need to come up with a layout that aligns the middle of a View to the bottom of other View in SwiftUI.
To make it more clear, all I need is something like this:
I guess the equivalent in a UIKit world would be:
redView.bottomAnchor.constraint(equalTo: whiteView.centerYAnchor)
Ive tried setting both in a ZStack
and offsetting the white View but it won’t work on all screen sizes for obvious reasons.
Any tips?
3
Answers
You can use
.aligmentGuide
(which is a tricky beast, I recommend this explanation)Here is your solution, its independent of the child view sizes:
You may try this:
Bascially the idea is to use coordinateSpace to get the frame of the bottom Rectangle and use geometryreader to get the offset needed by comparing the frame of top rectangle with the bottom one. Since we are using overlay and it is already aligned to the center horizontally, we just need to offset y to get the effect you want.
Based on OPs request in comment, this is a solution making use of a custom
Layout
.The
HalfOverlayLayout
takes two subview and places the second half height over the first. The size of the first subview is flexible. As this is my firstLayout
I’m not sure if I covered all possible size variants, but it should be a start.