当前位置 : 主页 > 手机开发 > ios >

ios – 带有闭包的UIGestureRecognizer

来源:互联网 收集:自由互联 发布时间:2021-06-11
我有视图,我想在其中执行向右滑动手势.不幸的是我收到错误 EXC_BAD_ACCESS.有人知道这里有什么问题吗?请看下面的代码. extension UIView { func addGestureRecognizerWithAction(nizer: 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")
}
网友评论