您可以在视图上创建通用扩展名,以轻松添加手势识别器。这只是一个例子,但看起来可能像这样
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)
}
}
}
要在视图上添加2次点击识别器,您只需调用:
let actionSelector = #selector(actionToExecute)
view.setGestureRecognizer(of: UITapGestureRecognizer.self, target: self, actionSelector: actionSelector, numOfTaps: 2)
您还可以轻松添加滑动识别器
view.setGestureRecognizer(of: UISwipeGestureRecognizer.self, target: self, actionSelector: actionSelector, swipeDirection: .down)
等等。只需记住目标必须链接到选择器。