Block scroll down in ScrollView - SwiftUI

↘锁芯ラ 提交于 2020-12-21 05:02:51

问题


How can I block scroll down and only allow scroll up in order to avoid seeing the white space over the rectangle on top when scrolling?

struct ContentView: View {
    
    var body: some View {
        GeometryReader { geo in
            ScrollView {
                Rectangle()
                .frame(width: geo.size.width, height: 400)
                .foregroundColor(.black)
                Spacer()
            }
        }
    }
}

回答1:


I assume you want to avoid bounces, here is possible approach (tested with 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) {}
}

Note: enclosingScrollView() helper is taken from my answer in How to scroll List programmatically in SwiftUI?



来源:https://stackoverflow.com/questions/63320572/block-scroll-down-in-scrollview-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!