2014-11-23 53 views
2

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

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

有另一种有效的方法,从而完成这项工作?

回答

7

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

你可以创建手势识别器,调用超级初始化,然后添加自己作为目标,我认为这将工作。

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

+2

Thx。创建手势识别器,调用超级初始化,然后添加自己作为目标确实有效。 – Drux 2014-11-23 11:47:05