我想将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'
}
是否有其他有效的语法可以完成这项工作?
答案 0 :(得分:7)
问题是您在self
准备就绪之前将self
添加为目标。
您可以创建手势识别器,调用超级init,然后将self添加为目标,我认为这样可行。
我个人倾向于将其设为lazy var
而不是let
。它保持封装,并节省您必须覆盖init方法。