I have a scrollView with a subview inside of it. I want any touch outside of the subview to make the scrollview scroll like it would in any other circumstance. But then when the touch is inside the subview I'd like no scroll to be registered (so I can use that touch to do dragging).
class ViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.backgroundColor = UIColor.red
scrollView.contentSize = CGSize(width: 1000, height: 1000)
let view = UIView(frame: CGRect(x: 600, y: 600, width: 200, height: 200))
view.backgroundColor = UIColor.blue
scrollView.addSubview(view)
}
}
So far I have tried many things to make this work. I have had some success with making customs classes for both the subview and the scrollview. In these classes I override the touch methods like so:
class MyScrollView: UIScrollView {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.isScrollEnabled = true
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
self.isScrollEnabled = true
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.isScrollEnabled = true
}
}
For the scrollview customclass I turned scrolling on and then for the subview custom class I turned it off. This works but there is a major problem that the first touch still goes ahead before the isScrollEnabled changes. This means when the scroll is off and you want to scroll you have to touch outside of the box and nothing happens and then do the same touch and the touch begins.
What I am looking for is a way to realise where a touch is, change the scroll settings and then on that same touch still scroll or not scroll dependent on what the setting is.
Cheers, any help is appreciated.
Probably the easiest way to do it is to add a dummy UIPanGestureRecognizer
to the blue view like this:
blueView.addGestureRecognizer(UIPanGestureRecognizer())
Even though there is no action, this will do the job because a touch will be handled by the subview first and only then handled by UIScrollView
's own UIPagGestureRecognizer
.