Can you attach a UIGestureRecognizer to multiple views?

前端 未结 12 882
忘了有多久
忘了有多久 2020-11-22 14:08
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTapTap:)];
[self.view1 addGestureRecognizer:tapGesture];         


        
12条回答
  •  情话喂你
    2020-11-22 14:52

    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(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.

提交回复
热议问题