'How can I make a view align it's center to the top of another view in SwiftUI?

So I want to have a view which overlaps another view, and has it's center Y aligned to the top of the view it's on top of.

The analogous layout constraints in UIKit would be the following:

let topView: UIView...
let bottomView: UIView...

NSLayoutConstraint.activate([
    topView.centerYAnchor.constraint(equalTo: bottomView.top)
])

How can I achieve this?



Solution 1:[1]

A possible approach is to use alignmentGuide modifier, which allows to fit specific internal alignment line to parent container. So by default containers have center alignment, so using top anchor instead for one of views result in align other's center to top.

Tested with Xcode 13.2 / iOS 15.2

demo

struct DemoView: View {
    var body: some View {
        ZStack {
            Rectangle().fill(.red)
                .frame(width: 300, height: 200)
                .alignmentGuide(VerticalAlignment.center) {   // << here !!
                    $0[VerticalAlignment.top]
                }
            Rectangle().fill(.green)
                .frame(width: 100, height: 80)
        }
        .border(Color.black)
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Asperi