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()
            }
        }
    }
}
2
  • If you are concerned about the white space you can add a background for your scroll view using ZStack. Commented Aug 8, 2020 at 22:10
  • even if it was dark or with an image I just don't want the view to scroll down Commented Aug 8, 2020 at 22:20

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I will try it soon. I just don't understand what should I put instead of enclosingScrollView
@asperi it is not working in Xcode 14
Yes, @venky is right. enclosingScrollView is missing. I don't see that a simple property modifier put into SwiftUI, do you?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.