如何在 SwiftUI 中设置 ScrollView 的 contentInset

Gig*_*ite 15 uiscrollview swift swiftui

我似乎无法找到如何设置 ScrollView 的 contentInset。我的目标是使我的 ScrollView 中的最后一个对象位于紫色主按钮上方。

https://i.stack.imgur.com/QfjZb.jpg

如果有命令,有人可以帮助如何将其实现到我下面的当前代码中。我将不胜感激您的帮助!

struct Overview: View {
    var body: some View {
        
        NavigationView {
            
            ScrollView(showsIndicators: false) {
                VStack(spacing: 10) {
                    ForEach(0..<5) {
                        Text("Item \($0)")
                            .foregroundColor(.white)
                            .font(.largeTitle)
                            .frame(width: 340, height: 200)
                            .background(Color("Boxes"))
                            .cornerRadius(10)
                    }
                }
                .frame(maxWidth: .infinity)
            }
            .navigationBarHidden(false)
            .navigationBarTitle("Overview", displayMode: .automatic)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

bte*_*pot 24

iOS 15 的 SwiftUI 现在有一个safeAreaInset修饰符。
\n它还可以正确调整滚动条。

\n
ScrollView(.vertical, showsIndicators: true) {\n    // scrollview\'s content\n}\n.safeAreaInset(edge: .bottom, spacing: 0) {\n    // some bottom-sticked content, or just \xe2\x80\x93\n    Spacer()\n        .frame(height: 44)\n}\n
Run Code Online (Sandbox Code Playgroud)\n


Mof*_*waw 16

您可以在ScrollView内容下方放置一个不可见的视图并为其添加底部填充。

例如,Color.clear底部填充为 300。

struct Overview: View {
    var body: some View {
        
        NavigationView {
            
            ScrollView(showsIndicators: false) {
                VStack(spacing: 10) {
                    ForEach(0..<5) {
                        Text("Item \($0)")
                            .foregroundColor(.white)
                            .font(.largeTitle)
                            .frame(width: 340, height: 200)
                            .background(Color("Boxes"))
                            .cornerRadius(10)
                    }

                    Color.clear.padding(.bottom, 300)
                }
                .frame(maxWidth: .infinity)
            }
            .navigationBarHidden(false)
            .navigationBarTitle("Overview", displayMode: .automatic)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然这有效,但滚动条不会像插入插图那样自行调整。 (11认同)
  • 我认为 Spacer(minLength: 300) 比空颜色更好 (9认同)
  • 这是一个黑客......并不是真正的解决方案 (5认同)

小智 12

只需添加一个paddingVStack嵌入在ScrollView.

使用带有嵌入堆栈的填充提供与内容插入相同的行为。

ScrollView(showsIndicators: false) {
    VStack(spacing: 10) {
        // Some content //
    }
    .padding(.bottom, 200)    // Choose a value that works for you
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为这应该是公认的答案 (5认同)