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 a much more 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With