SwiftUI:Spacer 在 ScrollView 上不起作用

Max*_*xim 22 scrollview ios swift swiftui vstack

如何在 VStack 中获得空间来将按钮固定在底部?

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)
    }
Run Code Online (Sandbox Code Playgroud)

我拥有的

我想要什么

8HP*_*HP8 39

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

\n

修复:

\n
    \n
  • VStack一个\xe2\x80\x99s ScrollViewViewminimumHeight的高度
  • \n
  • 滚动视图 width设置为视图也很重要 width
  • \n
\n
GeometryReader { geometry in\n    ScrollView(showsIndicators: false) {\n        VStack {\n        ...\n        }\n        .frame(minHeight: geometry.size.height)\n    }.frame(width: geometry.size.width)\n}\n
Run Code Online (Sandbox Code Playgroud)\n

这样,如果需要,内容的布局将能够超出视图的高度

\n


mah*_*han 15

使用GeometryReader

一个容器视图,将其内容定义为其自身大小和坐标空间的函数。 https://developer.apple.com/documentation/swiftui/geometryreader

GeometryReader { geometry in
    ScrollView {
        VStack() {
          -----
        }
        .frame(width: geometry.size.width, height: geometry.size.height)
    }
}
Run Code Online (Sandbox Code Playgroud)

这样做时,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)
    }

Run Code Online (Sandbox Code Playgroud)

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