private extension VerticalAlignment {
private enum Anchor : AlignmentID {
static func defaultValue(in d: ViewDimensions) -> CGFloat {
return d[VerticalAlignment.center]
}
}
static let anchor = VerticalAlignment(Anchor.self)
}
#Preview {
ZStack(alignment: .init(horizontal: .center, vertical: .anchor)) {
Color.clear
VStack(alignment: .leading) {
Rectangle()
.frame(width: 200, height: 200, alignment: .center)
.alignmentGuide(VerticalAlignment.anchor, computeValue: { d in d[VerticalAlignment.center] })
Rectangle()
.frame(width: 200, height: 200, alignment: .center)
}
}
.background(Color.yellow)
}
<aside> 💡 Color.clear is super important to expand ZStack as full size. even frame modifier as infinite size does not work. expanding element will be the key.
</aside>
SwiftUI: Pin to the top & bottom of a centered element