在ScrollView中阻止向下滚动-SwiftUI

时间:2020-08-08 21:56:50

标签: swift swiftui swiftui-scrollview

如何阻止向下滚动并仅允许向上滚动,以免滚动时看到顶部矩形上方的空白?

interface

1 个答案:

答案 0 :(得分:1)

我假设您想避免弹跳,这是可行的方法(已通过Xcode 12 / iOS 14测试)

struct ContentView: View {

    var body: some View {
        GeometryReader { geo in
            ScrollView {
                Rectangle()
                .frame(width: geo.size.width, height: 1800)
                .foregroundColor(.black)
                .background(ScrollViewConfigurator {
                    $0?.bounces = false               // << here !!
                })
                Spacer()
            }
        }
    }
}

struct ScrollViewConfigurator: UIViewRepresentable {
    let configure: (UIScrollView?) -> ()
    func makeUIView(context: Context) -> UIView {
        let view = UIView()
        DispatchQueue.main.async {
            configure(view.enclosingScrollView())
        }
        return view
    }

    func updateUIView(_ uiView: UIView, context: Context) {}
}

注意:enclosingScrollView()助手来自我在How to scroll List programmatically in SwiftUI?的答案中