ios - 将 UIGestureRecognizer 初始化为 Swift 中属性定义的一部分?

标签 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'
}

是否有另一种有效的语法可以完成这项工作?

最佳答案

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

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

我个人倾向于将其设为 lazy var 而不是 let。它保持封装并避免您必须重写 init 方法。

关于ios - 将 UIGestureRecognizer 初始化为 Swift 中属性定义的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27086779/

相关文章:

iOS gestureRecognizer 未处理 subview

ios - 如何判断 UIPageViewController 翻页是由于滑动/平移还是点击

ios - 从 Facebook 解析 Json

swift - 是否可以在一个枚举中快速分配不同类型的值

ios - PushViewController 无法正常工作

ios - touchesBegan 与 UITapGestureRecognizer

ios - 多行 UILabel 导致额外的填充

ios - 此类对于键 imageView 不符合键值编码

ios - 如何在 Twitter API 中隐藏来自 TimeLine 的推文

swift - 使用 CryptoTokenKit 读取 NFC (Mifare Classic 1K)