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)
This is 2 completely different ways of implementing user event handling in iOS apps.
1). addTarget()
- is method on UIControl
class, which is part of Target-Action Mechanism. More about that in documentation.
And you can't addTarget
tot any UIView
, only to UIControl
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 all UIControl
s such as UISegmetedControl
, UISlider
, etc.
Hope that I helped you.
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.
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 like UIControlEvents.TouchUpInside
.. and many other events.
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.
There are several benefits for addTarget:
- It is a build-in function. You don't need to initialize another object to do the same thing.
- You can set when to react to the action: "touchUpInside" or "touchDown" (or "valueChanged" for sliders).
- You can set the different appearances of the button (e.g. title text, title color, content image, background image, highlight tint) and the button only shows those statuses if addTarget is used.
Besides the benefits above, I think it's more like a coding convention for UIControl elements.