Quantcast
Channel: Can you attach a UIGestureRecognizer to multiple views? - Stack Overflow
Viewing all articles
Browse latest Browse all 14

Answer by Martin for Can you attach a UIGestureRecognizer to multiple views?

$
0
0

You could create a generic extension on view to add gesture recognizers easily.This is just an example but it could look like this

extension UIView {    func setGestureRecognizer<Gesture: UIGestureRecognizer>(of type: Gesture.Type, target: Any, actionSelector: Selector, swipeDirection: UISwipeGestureRecognizer.Direction? = nil, numOfTaps: Int = 1) {    let getRecognizer = type.init(target: target, action: actionSelector)    switch getRecognizer {    case let swipeGesture as UISwipeGestureRecognizer:        guard let direction = swipeDirection else { return }        swipeGesture.direction = direction        self.addGestureRecognizer(swipeGesture)    case let tapGesture as UITapGestureRecognizer:        tapGesture.numberOfTapsRequired = numOfTaps        self.addGestureRecognizer(tapGesture)    default:        self.addGestureRecognizer(getRecognizer)    }  }}

To add a 2 tap recognizer on a view you would just call:

let actionSelector = #selector(actionToExecute)view.setGestureRecognizer(of: UITapGestureRecognizer.self, target: self, actionSelector: actionSelector, numOfTaps: 2)

You could also easily add a swipe recognizer

view.setGestureRecognizer(of: UISwipeGestureRecognizer.self, target: self, actionSelector: actionSelector, swipeDirection: .down)

and so on.Just remember that the target must be linked to the selector.


Viewing all articles
Browse latest Browse all 14

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>