如何在SwiftUI中进行这种简单的布局?

时间:2019-12-11 20:31:28

标签: ios swift swiftui

我需要一个以屏幕为中心的MainView,以及一个灵活的HeaderView,它占据了MainView和屏幕顶部之间的剩余空间(请参见下文)。如何在SwiftUI中完成此操作?

enter image description here

入门代码:

struct TestView: View {
    var body: some View {
        ZStack {
            //Center Line
            Divider()

            VStack {
                Text("HeaderView")
                    .border(Color.orange, width: 6)
                Text("MainView")
                    .frame(width: 400, height: 200, alignment: .center)
                    .border(Color.red, width: 6)
            }
        }

    }
}

1 个答案:

答案 0 :(得分:3)

VStack {
    // Let the HeaderView expand to whatever is available, in both directions
    Text("HeaderView")
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .border(Color.orange, width: 6)

    Text("MainView")
        .frame(maxWidth: .infinity) // Added to allow this view to expand horizontally
        .frame(height: 200) // alignment is not needed here.
        .border(Color.red, width: 6)

    // And then add a Spacer() at the end that also has flexible height
    Spacer()
        .frame(maxHeight: .infinity)
}

由于Main的高度固定,因此它将首先获得其请求的高度。然后,由于Header和Spacer具有同等的优先级和灵活性,因此它们各自将获得剩余的一半,从而使Main垂直居中。