将 UIGestureRecognizer 初始化为 Swift 中属性定义的一部分? [英] Initialize UIGestureRecognizer as part of property definition in Swift?

查看:28
本文介绍了将 UIGestureRecognizer 初始化为 Swift 中属性定义的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想初始化一个 UIPanGestureRecognizer 作为 UIViewController 的属性定义的一部分,这样我就不必将它声明为可选的(因为我会如果初始化仅发生在 viewDidLoad 中).

I would like to initialize a UIPanGestureRecognizer as part of a UIViewController´s property definition, so that I don't have to declare it optional (as I would have to if initialization occurs only in viewDidLoad).

以下两次尝试都在编译时失败(我使用的是最新版本的 Xcode):

Both of the following two attempts fail at compile time (I am using the latest version of Xcode):

-- 1st attempt
class TestController: UIViewController {

    let panGestureRecognizer: UIPanGestureRecognizer

    required init(coder: NSCoder) {
        super.init(coder: coder)
        panGestureRecognizer = UIPanGestureRecognizer(  target: self, action: "handlePan:")
        // fails with "Property 'self.panGestureRecognizer' not initialized at super.init call' or
        // fails with "'self' used before super.init call'
        // depending on the order of the two previous statements
    }
}

-- 2st attempt
class TestController: UIViewController {

    let panGestureRecognizer = UIPanGestureRecognizer(target:self, action: "handlePan:")
    // fails with "Type 'TestController -> () -> TestController!' does not conform to protocol 'AnyObject'
}

还有其他有效的语法可以完成这项工作吗?

Is there another valid syntax that would do the job?

推荐答案

问题是您在 self 准备好之前将 self 添加为目标.

The problem is that you're adding self as a target before self is ready.

您可以创建手势识别器,调用 super init,然后将 self 添加为目标,我认为这会起作用.

You could create the gesture recogniser, call super init, then add self as a target, I think that would work.

我个人更倾向于将其设为 lazy var 而不是 let.它保持封装状态,并且无需覆盖 init 方法.

I'd be inclined to make this a lazy var rather than a let, personally. It keeps it encapsulated and saves you having to override init methods.

这篇关于将 UIGestureRecognizer 初始化为 Swift 中属性定义的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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