上篇讲了Button的快捷处理点击事件,有没看过的朋友可以过去看一下
iOS Button快捷处理点击事件 与View快捷处理添加手势(一)
这一篇主要给大家分享一下快捷处理View手势点击事件,通常我们在view上添加手势是这样的(假如给TapView添加手势,我们得这样写):
let tapView = UIView()
self.addSubview(tapView)
let tapGes = UITapGestureRecognizer.init(target: self, action:#selector(tapAction))
tapView.addGestureRecognizer(tapGes)
func tapAction(){
//点击操作
}
既要添加视图还要添加手势,最后还要写一个响应手势的方法,极不方便,如果我们能把所有的整合到一块,减少代码量,还是蛮舒服的,就像这样:
let tapView = UIView()
tapView.addGesClosure {
//点击操作
}
self.addSubview(tapView)
上面所有关于添加单击手势的就被整合成一句代码,希望能帮到感兴趣的朋友,其实原理和上篇button是一样,代码贴出来分享给大家,这次的就只有Swift版了,OC的大家自己对照写一下吧,自己建一个Swift文件,复制一下代码就好了
import Foundation
import UIKit
public extension UITapGestureRecognizer{
private struct AssociatedKeys{
static var buttonTouch = "buttonTouch"
}
typealias TouchedClosure = ()->Void
public func addTouchClosure(closure:TouchedClosure?) {
objc_setAssociatedObject(self,&AssociatedKeys.buttonTouch,closure,.OBJC_ASSOCIATION_COPY_NONATOMIC)
self.addTarget(self, action: #selector(actionTouch))
}
@objc private func actionTouch(){
if let closure:TouchedClosure = objc_getAssociatedObject(self,&AssociatedKeys.buttonTouch) as? UITapGestureRecognizer.TouchedClosure{
closure()
}
}
}
extension UIView {
func addGesClosure(closure:GesAddClosure?){
self.isUserInteractionEnabled = true
let ges = UITapGestureRecognizer()
ges.addTouchClosure {
closure!()
}
self.addGestureRecognizer(ges)
}
}
一些小东西,希望能帮助到大家