Home > OS >  ScrollView touch works despite all other touch is disabled
ScrollView touch works despite all other touch is disabled

Time:07-05

So my goal is to disable touch events for everything on screen and I don't want to use .disable on every view or to use Color.black.opacity(0.00001) because of the code smell. I want it to be a block that isn't visible for the user like if I would overlay Color.clear over the whole view. And I want it to behave like if I were to use Color.black.opacity(0.1) with it disabling touch events on every view underneath.

If I for example use a ZStack with:

  • Color.black.opacity(0.2) every view underneath will no longer register touch events. (I want this, but it should be transparent)
  • Color.black.opacity(0) every view underneath will register touch events.
  • Color.black.opacity(0).contentShape(Rectangle()), some events will register, some won't, for example buttons won't work though scrolling in a ScrollView, or using a toggle will still work.

Here is some example code

struct ContentView: View {

@State var numberOfRows: Int = 10

var body: some View {
    ZStack {
        Color.white
        
        ScrollView {
            VStack {
                ForEach(0..<numberOfRows, id: \.self) { (call: Int) in
                    Text(String(call))
                        .frame(maxWidth: .infinity)
                }
            }
        }
        
        Button(action: {
            numberOfRows  = 1
        }) {
            Color.blue
                .frame(width: 300, height: 300)
        }
        
        Color.black.opacity(0) // <- change this to 0.x to disable all touch
            .contentShape(Rectangle()) // <- Remove this line to make blue button work (opacity needs to be 0)
        }
    }
}

Why is scrollview still receiving touch events and why is buttons not?

Is there a way to make my touch events for every view underneath, disabled?

CodePudding user response:

Use instead (tested with Xcode 13.4 / iOS 15.5)

Color.clear
//    .ignoresSafeArea(.all)  // << if need all screen space
    .contentShape(Rectangle())
    .highPriorityGesture(DragGesture(minimumDistance: 0))
  • Related