如何在SwiftUI中将一个视图的中间与另一个视图的底部对齐?

h43kikqp  于 2023-01-04  发布在  Swift
关注(0)|答案(2)|浏览(217)

因此,基本上我需要在SwiftUI中设计一个布局,使一个视图的中间与另一个视图的底部对齐。为了使它更清楚,我需要的是这样的布局:

我猜在UIKit世界中的等价物是:

redView.bottomAnchor.constraint(equalTo: whiteView.centerYAnchor)

我试过在ZStack中设置和偏移白色视图,但由于明显的原因,它不会在所有屏幕尺寸上工作。
有什么建议吗?

k4aesqcs

k4aesqcs1#

可以使用.aligmentGuide(这是一个棘手的野兽,我推荐this explanation
下面是您的解决方案,它与子视图大小无关:

struct ContentView: View {
    
    var body: some View {
        
        ZStack(alignment: .bottom) { // subviews generally aligned at bottom
            redView
            whiteView
                // center of this subview aligned to .bottom
                .alignmentGuide(VerticalAlignment.bottom, 
                                computeValue: { d in d[VerticalAlignment.center] }) 
        }
        .padding()
    }
    
    var redView: some View {
        VStack {
            Text("Red View")
        }
        .frame(maxWidth: .infinity)
        .frame(height: 200)
        .background(Color.red)
        .cornerRadius(20)
    }
    
    var whiteView: some View {
        VStack {
            Text("White View")
        }
        .frame(maxWidth: .infinity)
        .frame(width: 250, height: 100)
        .background(Color.white)
        .cornerRadius(20)
        .overlay(RoundedRectangle(cornerRadius: 20).stroke())
    }
    
}
jslywgbw

jslywgbw2#

你可以试试这个:

ZStack {
        Rectangle()
            .frame(width: 300, height: 400)
            .overlay(
                GeometryReader { proxy in
                    
                    let offsetY = proxy.frame(in: .named("back")).midY
                    Rectangle()
                        .fill(Color.red)
                        .offset(y: offsetY)
                }
                    .frame(width: 150, height: 140)
                , alignment: .center)
    }
    .coordinateSpace(name: "back")

基本上,这个想法是使用coordinateSpace来获得底部矩形的框架,并使用geometryreader通过比较顶部矩形的框架和底部矩形的框架来获得所需的偏移。由于我们使用了overlay,并且它已经水平对齐到中心,因此我们只需要偏移y来获得想要的效果。

相关问题