Search code examples
iosswiftuiscrollview

How to make realy exclusive touch for a view inside uiscrollview?


I'm going to show a chart inside a scroll view that when I am dragging on a chart, scroll view doesn't work.

I've already tried to use isExclusiveTouch on my view but doesn't work as my expected.

When I am going to touch on a chart and drag my finger on it to display other values, scroll view catch my touch event and scrolling happen.


Solution

  • I found my answer. Hope this helps.

    If you want disable UIScrollView scrolling you should override gestureRecognizerShouldBegin method. Detect which view touched and if you want to stop scrolling return false otherwise you must call super.gestureRecognizerShouldBegin(gestureRecognizer).

    In my case I defined a constant variable in my class and used it as tag in a view that i want to disable scrolling on it.

    class CustomScrollView: UIScrollView {
    
        static let EXCEPTION_FOR_SCROLLING = 1
    
        var exceptionViews: [UIView]?
    
        override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
            if let view = gestureRecognizer.view {
                if shouldCancelTouch(view, gestureRecognizer) {
                    return false
                }
            }
            return super.gestureRecognizerShouldBegin(gestureRecognizer)
        }
    
        private func shouldCancelTouch(_ view: UIView, _ gestureRecognizer: UIGestureRecognizer) -> Bool {
            if (exceptionViews?.contains(view) ?? false) || view.tag == CustomScrollView.EXCEPTION_FOR_SCROLLING {
                return true
            } else {
                for i in 0..<view.subviews.count {
                    if view.subviews[i].frame.contains(gestureRecognizer.location(in: view)) {
                        if shouldCancelTouch(view.subviews[i], gestureRecognizer) {
                            return true
                        }
                    }
                }
            }
    
            return false
        }
    
    }