我想将 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'
}
是否有另一种有效的语法可以完成这项工作?
最佳答案
问题是您在 self
准备好之前将 self
添加为目标。
您可以创建手势识别器,调用 super init,然后将 self 添加为目标,我认为这可行。
我个人倾向于将其设为 lazy var
而不是 let
。它保持封装并避免您必须重写 init 方法。
关于ios - 将 UIGestureRecognizer 初始化为 Swift 中属性定义的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27086779/