Can anyone clarify the difference between these 2 ways of triggering a function when tapping a view?
1)
myView.addTarget(self, action: #selector(myFunctionToTrigger(_:)), forControlEvents: UIControlEvents.TouchUpInside)
2)
let tapGesture = UITapGestureRecognizer(target: self, action:
#selector(myFunctionToTrigger(_:)))
myView.addGestureRecognizer(tapGesture)
Here is the difference
For
UITapGestureRecognizer
you can add event for specified gestures like UITapGestureRecognizer,UIPanGestureRecognizer
... and many other gestures .Where as For
UIView
addTarget()
you can add target for specified events likeUIControlEvents.TouchUpInside
.. and many other events.There are several benefits for addTarget:
Besides the benefits above, I think it's more like a coding convention for UIControl elements.
These two method work at two different levels of abstraction:
addTarget:action:forControlEvents
is the lower level that provides isolated events. Several of these events must be combined and interpreted to detect more complex gestures like swiping or pinching.addGestureRecognizer
works at a higher level closer to what an app usually needs. It adds specific gesture recoginzer that listen to the low level events, detect gestures and deliver specific information about the gesture.In the case of a tap, the difference is minor. But when it comes to swiping, pinching and a combination of tapping, swiping, pinching (e.g. in a image viewr or in a map app), one or more gesture recoginzers are the way to go.
This is 2 completely different ways of implementing user event handling in iOS apps.
1).
addTarget()
- is method onUIControl
class, which is part of Target-Action Mechanism. More about that in documentation.And you can't
addTarget
tot anyUIView
, only toUIControl
subclasses.2).
UIGestureRecognizer
subclasses is just simply a mechanism to detect and distinguish user gestures on specific view.Main difference between them that Gesture Recognizers can detect more complex events like swipe or pinch or zoom, but
-addTarget
is much efficient way to detect user activity, also it provides the same level of interface for allUIControl
s such asUISegmetedControl
,UISlider
, etc.Hope that I helped you.
Pavel's answer is correct, you can only add a target to a UIControlView, which is a subclass of UIView. A UIGestureRecognizer can be added to any UIView.
Codo's answer that a target is lower level than a gesture is wrong, gestures are the lower level touch support. A UIControl uses gestures to make addTarget:action:forControlEvents work.