这个类功能就是封装UISwipeGestureRecognizer,添加上下左右4种滑动手势及相应的时间,这些都不重要,重要的是:
- typealias sendValueClosure = (swipeGesture: UISwipeGestureRecognizer) -> Void</span>
- class SwipeGesture:NSObject {
- //声明一个闭包
- var myClosure: sendValueClosure?
- //下面的方法需要传入上个界面的someFunctionThatAClosure函数指针
- func initWithClosure(closuer: sendValueClosure?) {
- //讲函数指针赋值给myClosure闭包,该闭包中覆盖了someFunctionThatTakesAClosure函数中的局部变量等引用
- self.myClosure = closuer
- }
- func setSwipeGesture(view:UIView){
- //设置手势
- let swipeRight = UISwipeGestureRecognizer(target: self,action: "respondToSwipeGesture:")
- swipeRight.direction = UISwipeGestureRecognizerDirection.Right
- view.addGestureRecognizer(swipeRight)
- let swipeLeft = UISwipeGestureRecognizer(target: self,action: "respondToSwipeGesture:")
- swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
- view.addGestureRecognizer(swipeLeft)
- let swipeUp = UISwipeGestureRecognizer(target: self,action: "respondToSwipeGesture:")
- swipeUp.direction = UISwipeGestureRecognizerDirection.Up
- view.addGestureRecognizer(swipeUp)
- let swipeDown = UISwipeGestureRecognizer(target: self,action: "respondToSwipeGesture:")
- swipeDown.direction = UISwipeGestureRecognizerDirection.Down
- view.addGestureRecognizer(swipeDown)
- }
- //事件
- func respondToSwipeGesture(gesture: UIGestureRecognizer){
- if let swipeGesture = gesture as? UISwipeGestureRecognizer {
- if let closure = self.myClosure {
- closure(swipeGesture: swipeGesture)
- }
- }
- }
- }
声明的闭包myClosure在类的最上面那句代码:
initWithClosure(closure: sendValueClosure)这个函数是被我们UIView源文件调用的。
- typealias sendValueClosure = (swipeGesture: UISwipeGestureRecognizer) -> Void
下面respondToSwipeGesture(gesture:UIGestureRecognizer)事件触发的时候,里面的
- if let closure = self.myClosure {
- closure(swipeGesture: swipeGesture)
- }
是把 UISwipeGestureRecognizer 当做参数返回给闭包。
是的,就是这么简单。。手势不是目的,封装不是目的,目的是学会用闭包实现数据监听及传送数据。
- //实例化类
- let mySwipeGesture = SwipeGesture()
- // 给 UIView 添加手势
- mySwipeGesture.setSwipeGesture( yourView)
- //调用闭包监听事件
- mySwipeGesture.initWithClosure { (swipeGesture) -> Void in
- switch swipeGesture.direction {
- case UISwipeGestureRecognizerDirection.Right:
- print("Swiped right")
- case UISwipeGestureRecognizerDirection.Left:
- print("Swiped left")
- case UISwipeGestureRecognizerDirection.Up:
- print("Swiped up")
- case UISwipeGestureRecognizerDirection.Down:
- print("Swiped down")
- default:
- break
- }
- }