As my scrollview is very small (only 100p tall), the hitTest
method gets the whole ViewController which is not what I want. This solution covers any size of ScrollView and is done using Swift 4:
class ScrollViewContainer: UIView {
@IBOutlet weak var scrollView: UIScrollView!
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
guard self.bounds.contains(point) else {
return super.hitTest(point, with: event)
}
guard self.scrollView.frame.contains(point) else {
return self.scrollView
}
return super.hitTest(point, with: event)
}
}
The first Guard
returns the default UIView
hitTest
if the hit is outside of its boundaries.
The second one returns the UIScrollView
if the hit is inside of my container but outside of the ScrollView (which is exactly the objective of this question).
And if the hit is inside of the ScrollView, there is no need to do anything different, just let UIView handle it with its default implementation.
The only thing that needs to be handled is when your touch is inside of the container but outside of the scrollview.
This code can be reduced to only one guard
, but I thought that this way was clearer to explain the logic.