Dru*_*rux 2 initializer uigesturerecognizer ios swift
我想初始化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'
}
Run Code Online (Sandbox Code Playgroud)
是否有另一种有效的语法可以完成这项工作?
问题是您在准备好self之前添加为目标self.
您可以创建手势识别器,调用超级init,然后将self添加为目标,我认为这样可行.
我个人倾向于把它变成一个lazy var而不是一个let.它保持封装,并节省您必须覆盖init方法.
| 归档时间: |
|
| 查看次数: |
1828 次 |
| 最近记录: |