带有闭包的UIGestureRecognizer [英] UIGestureRecognizer with closure

查看:46
本文介绍了带有闭包的UIGestureRecognizer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have as view, in which I want to perform a swipe right gesture. Unfortunately I receive the error EXC_BAD_ACCESS. Does anybody know what's wrong here ? Please a look at the code below.

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

推荐答案

对于那些不喜欢关联对象和其他棘手东西的人,我有一个小型手势识别器,不需要任何麻烦.而且它不需要存储在某个地方.像常规GR一样工作.尽管它有一些限制-它是从 UITapGestureRecognizer 继承的,并且他只知道如何处理水龙头.但是我们经常需要所有的类型吗?我个人不是.

For those who does not like associated objects and other tough stuff I have a small gesture recogniser that does not need any hustle. And it doesn't need to be stored somewhere. Works like a regular GR. Though it has some limitations - it's inherited from UITapGestureRecognizer and he knows only how to handle taps. But do we often need all the types there are? Personally me not.

final class BindableGestureRecognizer: UITapGestureRecognizer {
    private var action: () -> Void

    init(action: @escaping () -> Void) {
        self.action = action
        super.init(target: nil, action: nil)
        self.addTarget(self, action: #selector(execute))
    }

    @objc private func execute() {
        action()
    }
}

用法示例:

    let gestureRecognizer = BindableGestureRecognizer {
        print("It's alive!")
    }
    self.view.addGestureRecognizer(gestureRecognizer)

如果出现一些更有意义的行,请不要忘记[弱自我].我们不想创建那些不死伙伴.

In case some more meaningful lines are presented, don't forget about [weak self]. We don't want to create those undead buddies.

    let colorGestureRecognizer = BindableGestureRecognizer { [weak self] in
        self?.view.backgroundColor = .red
    }
    self.view.addGestureRecognizer(colorGestureRecognizer)

对我来说似乎很方便,可以从那些 @objc 衬里中净化视图控制器,并使它变得更多一点..反应灵敏吗?

Seems handy for me to purify our view controller from those @objc one liners and to become a bit more.. reactive?

这篇关于带有闭包的UIGestureRecognizer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆