在Swift中初始化UIGestureRecognizer作为属性定义的一部分?

时间:2014-11-23 07:55:31

标签: ios swift uigesturerecognizer initializer

我想将UIPanGestureRecognizer初始化为UIViewController属性定义的一部分,这样我就不必将其声明为可选(因为如果初始化只发生在viewDidLoad)。

以下两次尝试都在编译时失败(我使用的是最新版本的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'
}

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

1 个答案:

答案 0 :(得分:7)

问题是您在self准备就绪之前将self添加为目标。

您可以创建手势识别器,调用超级init,然后将self添加为目标,我认为这样可行。

我个人倾向于将其设为lazy var而不是let。它保持封装,并节省您必须覆盖init方法。