Referring to the Apple documentation on UIResponder, all UIView objects (which includes UIWindow), UIApplication object, UIViewController objects are all instances of UIResponder. To handle a specific type of event, a responder must override the corresponding methods.
In our case touches
is our type of event. So our responder should implement the following methods.
touchesBegan(:with:), touchesMoved(:with:), touchesEnded(:with:), and touchesCancelled(:with:)
Since we only wish to know when a user has touched a particular view, we only need to implement touchesBegan(_:with:)
. Since we are not overriding the other methods we must call super.touchesBegan(touches, with: event)
. If we were overriding ALL of the other methods, we wouldn't be required to call super
.
Looking at touchesBegan(_:with:)
the parameter touches
is a set of UITouch instances. Each instance represents the touches for the starting phase of the event, which is represented by the parameter event
.
For touches in a view, this set contains only one touch by default. Hence touches.first
is the only UITouch instance in the set. We then access the property view
, this represents the view or window in which the touch occurred. Lastly we compare the view that has been touched with your desired view.
It should be noted that if you wish to receive multiple touches- you must set the view's isMultipleTouchEnabled
property to true
. Then the set of touches
will have more than one UITouch instance and you will have to handle that accordingly.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if let touch = touches.first, touch.view == myView {
// Do something
}
}
UIScrollView
:) – Ton