1

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()
            }
        }
    }
}
pawello2222
  • 46,897
  • 22
  • 145
  • 209
xmetal
  • 681
  • 6
  • 16

1 Answers1

9

Update: re-tested with Xcode 13.3 / iOS 15.4

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?

Test module in project is here

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690