简单封装UIGestureRecognizer
每次对View添加点击方法,都学要写一堆代码,所以就自己封装了一个简单的对view添加点击事件的方法
不多BB,直接上代码
typealias viewAction = (UIGestureRecognizer)->()
extension UIView {
enum GestureENUM {
case tap //点击
case long //长按
case pan //拖拽
case roation //旋转
case swipe //轻扫
case pinch //捏合
}
private struct AssociatedKeys {
static var actionKey = "gestureKey"
}
@objc dynamic var action:viewAction? {
set {
objc_setAssociatedObject(self, &AssociatedKeys.actionKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
}
get {
if let action = objc_getAssociatedObject(self, &AssociatedKeys.actionKey) as? viewAction {
return action
}
return nil
}
}
@objc func viewTapAction(gesture: UIGestureRecognizer) {
if action != nil {
action!(gesture)
}
}
func addGesture( _ gesture : GestureENUM , response:@escaping viewAction) {
self.isUserInteractionEnabled = true
switch gesture {
case .tap:
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(viewTapAction(gesture:)))
tapGesture.numberOfTouchesRequired = 1
tapGesture.numberOfTapsRequired = 1
self.addGestureRecognizer(tapGesture)
self.action = response
case .long:
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(viewTapAction(gesture:)))
self.addGestureRecognizer(longPress)
self.action = response
case .pan:
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(viewTapAction(gesture:)))
self.addGestureRecognizer(panGesture)
self.action = response
case .roation:
let roation = UIRotationGestureRecognizer(target: self, action: #selector(viewTapAction(gesture:)))
self.addGestureRecognizer(roation)
self.action = response
case .swipe:
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(viewTapAction(gesture:)))
swipe.direction = .down
self.addGestureRecognizer(swipe)
self.action = response
case .pinch:
let pinch = UIPinchGestureRecognizer(target: self, action: #selector(viewTapAction(gesture:)))
self.addGestureRecognizer(pinch)
self.action = response
}
}
}
调用方式
/// 添加点击方法
view.addGesture(.tap) { (tapACtion) in
// 点击实现方法
<#code#>
}
/// 添加拖拽手势
self.view.addGesture(.pan) { (panAction) in
<#code#>
}
…其他方式通上,只需要传入不同的枚举值即可(暂时最常用的就是轻拍手势,其他方式没有逐步试验,有问题,欢迎批评)