首页 > 解决方案 > 如何在 SwiftUI 中创建粘底?

问题描述

我正在尝试在 swiftUI 中创建粘性页脚,其中屏幕的其他部分是可滚动的,但在页脚中有一个带有按钮和其他元素的视图,这些元素应该被修复。

在此处输入图像描述

谢谢你的帮助。

标签: iosswiftswiftui

解决方案


如果我理解正确,您想要做的是垂直堆叠(VStack)

  1. 滚动视图
  2. 另一个 VStack(带有 Toggle 和 Button),在底部对齐:
VStack {
        ScrollView {...} // 1
        VStack {         // 2
             Toggle(...)
             Button(...)
        }
        .frame(alignment: .bottom)
}

举个例子:

struct SwiftUIView: View {
    @State private var checked: Bool = false
    let text = String(repeating: "blabla ", count: 20)
    
    var body: some View {
        VStack {
            ScrollView {
                ForEach((1...100), id: \.self) {_ in
                    Text(text)
                }
            }
            
            VStack {
                Toggle(isOn: $checked, label: {
                    Text("I have read...")
                })
                Button("Enter") {
                    // action
                }
                .frame(maxWidth: .infinity)
                .padding(.vertical)
                .background(Color.red)
            }
            .padding()
            .border(Color.black)
            .frame(alignment: .bottom)
        }
    }
}

你的例子


推荐阅读