如何使一个视图的中心与 SwiftUI 中另一个视图的顶部对齐?

发布于 2025-01-17 06:20:26 字数 262 浏览 2 评论 0原文

所以我想要一个与另一个视图重叠的视图,并且它的中心 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

听风念你 2025-01-24 06:20:26

一种可能的方法是使用alignmentGuide修饰符,它允许将特定的内部对齐线适合父容器。因此,默认情况下,容器具有中心对齐方式,因此对其中一个视图使用顶部锚点会导致其他视图的中心与顶部对齐。

使用 Xcode 13.2 / iOS 15.2 进行测试

演示

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)
    }
}

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)
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文