【问题标题】:SwiftUI: Spacer doesn't work at ScrollViewSwiftUI:Spacer 在 ScrollView 中不起作用
【发布时间】:2021-09-10 00:32:22
【问题描述】:

如何在 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)
    }

what I have

what I want to have

【问题讨论】:

    标签: ios swift swiftui scrollview vstack


    【解决方案1】:

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

    修复:

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

    如果需要,内容可以在视图高度之外进行布局

    【讨论】:

    • 乍一看,这看起来不错并且有效。可悲的是,至少在 iOS 15 中,由于这种方法,VStack 中的文本视图可能会被压缩,从而导致文本被截断。测试:在 Stack 中放置几块 Text 视图,这样内容就相当于一个屏幕高度,一些 Text 视图会被压缩,而在我的情况下,一些不会。
    【解决方案2】:

    使用GeometryReader

    将其内容定义为自身大小和坐标空间的函数的容器视图。 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 按钮位于底部,无论如何。因此,您无需执行任何操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多