微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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")
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐