Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between UITapGestureRecognizer and addTarget

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)

like image 259
Daniele B Avatar asked Mar 12 '23 08:03

Daniele B


1 Answers

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 UIControls such as UISegmetedControl, UISlider, etc.

Hope that I helped you.

like image 112
Pavel Gatilov Avatar answered Mar 15 '23 19:03

Pavel Gatilov