如何使一个视图的中心与 SwiftUI 中另一个视图的顶部对齐?
所以我想要一个与另一个视图重叠的视图,并且它的中心 Y 与其所在视图的顶部对齐。
UIKit 中的类似布局约束如下:
let topView: UIView...
let bottomView: UIView...
NSLayoutConstraint.activate([
topView.centerYAnchor.constraint(equalTo: bottomView.top)
])
我怎样才能实现这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种可能的方法是使用alignmentGuide修饰符,它允许将特定的内部对齐线适合父容器。因此,默认情况下,容器具有中心对齐方式,因此对其中一个视图使用顶部锚点会导致其他视图的中心与顶部对齐。
使用 Xcode 13.2 / iOS 15.2 进行测试
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