ios – 带有闭包的UIGestureRecognizer

我有视图,我想在其中执行向右滑动手势.不幸的是我收到错误
EXC_BAD_ACCESS.有人知道这里有什么问题吗?请看下面的代码.

extension UIView {

    func addGestureRecognizerWithAction(nizer: UIGestureRecognizer,action:() -> ()) {

        class Invoker {
            var action:() -> ()
            init(action:() -> ()) {
                self.action = action
            }
            func invokeTarget(nizer: UIGestureRecognizer) {
                self.action()
                println("Hi from invoker")
            }
        }
        addGestureRecognizer(nizer)
        nizer.addTarget(Invoker(action),action: "invokeTarget:")
    }
}

class BugView: UIView {

    override func awakeFromNib() {
        super.awakeFromNib()

        var swipeRight = UISwipeGestureRecognizer()
        swipeRight.direction = UISwipeGestureRecognizerDirection.Right
        self.addGestureRecognizerWithAction(swipeRight) {
            println("Hi from the gesture closure")
        }
    }
}

解决方法

最后返回true是对的.在他上面的回答中,他指出我正确的方向,建议让Invoker成为NSObject的子类.

但这不是我在代码中唯一的错误.我发现当滑动发生时,旨在处理事件的Invoker对象已经从内存中消失了.我认为关闭它的提法并没有像它应该的那样被捕获.现在我想出了另一种实现此功能方法,我想与您分享

class UIGestureRecognizerWithClosure: NSObject {  // must subclass NSObject otherwise error: "class does not implement methodSignatureForSelector: -- " !!

    var closure:() -> ()

    init(view:UIView,nizer: UIGestureRecognizer,closure:() -> ()) {
        self.closure = closure
        super.init()
        view.addGestureRecognizer(nizer)
        nizer.addTarget(self,action: "invokeTarget:")
    }

    func invokeTarget(nizer: UIGestureRecognizer) {
        self.closure()
    }
}

代码显示了如何使用代码

var swipeRight = UISwipeGestureRecognizer()
swipeRight.direction = UISwipeGestureRecognizerDirection.Right

// swipeWrapper has to be defined as a property: var swipeWrapper:UIGestureRecognizerWithClosure?
// -> this is needed in order to keep the object alive till the swipe event occurs
swipeWrapper = UIGestureRecognizerWithClosure(view: self,nizer:swipeRight) {
    println("Hi from the gesture closure")
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...