0

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

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

1 回答 1

7

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?

于 2020-08-09T05:14:13.470 回答