SwiftUI:Spacer 在 ScrollView 中不起作用

SwiftUI: Spacer doesn't work at ScrollView

如何让 VStack 中的 space 将按钮固定在底部?

ScrollView {
        VStack() {
            Text("Title_1")
                .padding(.bottom, 35.0)
            Text("Title_2")
                .padding(.bottom, 32.0)
            Text("Title_3")
                .padding(.bottom, 27.0)
            
            Spacer()
            Button(action: { print("ACTION") }) {
                Text("OK")
                    .font(.title)
                    .fontWeight(.semibold)
                    .foregroundColor(Color.red)
                    
            }
            .frame(height: 35)
            .cornerRadius(8.0)
            .padding(.bottom, 25.0)
        }
        .frame(maxWidth: .infinity)
    }

what I have

what I want to have

使用GeometryReader

A container view that defines its content as a function of its own size and coordinate space. https://developer.apple.com/documentation/swiftui/geometryreader

GeometryReader { geometry in
    ScrollView {
        VStack() {
          -----
        }
        .frame(width: geometry.size.width, height: geometry.size.height)
    }
}

这样,VStack 就全屏显示了。


您可能不需要使用 ScrollView,因为您不需要滚动查看其内容。

    var body: some View {
        
        VStack() {
            Text("Title_1")
                .padding(.bottom, 35.0)
            Text("Title_2")
                .padding(.bottom, 32.0)
            Text("Title_3")
                .padding(.bottom, 27.0)
            
            Spacer()
            Button(action: { print("ACTION") }) {
                Text("OK")
                    .font(.title)
                    .fontWeight(.semibold)
                    .foregroundColor(Color.red)
                
            }
            .frame(height: 35)
            .cornerRadius(8.0)
            .padding(.bottom, 25.0)
        }
        .frame(maxWidth: .infinity)
    }

但是如果您的内容的高度超过屏幕高度,则 OK 按钮位于底部,无论如何。因此,您无需执行任何操作。

ScrollView 给出了 VStack infinite 可能的高度。这就是垫片不起作用的原因。

修复:

  • VStack一个minimumHeight,这是ScrollViewView[=32的高度=]
  • 同样重要的是将 scrollview 的 width 设置为 view 的 width
GeometryReader { geometry in
    ScrollView(showsIndicators: false) {
        VStack {
        ...
        }
        .frame(minHeight: geometry.size.height)
    }.frame(width: geometry.size.width)
}

这样内容将能够在需要时超出视图的高度进行布局