Initialize UIGestureRecognizer as part of property definition in Swift?

不打扰是莪最后的温柔 提交于 2019-12-11 01:10:55

问题


I would like to initialize a UIPanGestureRecognizer as part of a UIViewController´s property definition, so that I don't have to declare it optional (as I would have to if initialization occurs only in viewDidLoad).

Both of the following two attempts fail at compile time (I am using the latest version of 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'
}

Is there another valid syntax that would do the job?


回答1:


The problem is that you're adding self as a target before self is ready.

You could create the gesture recogniser, call super init, then add self as a target, I think that would work.

I'd be inclined to make this a lazy var rather than a let, personally. It keeps it encapsulated and saves you having to override init methods.



来源:https://stackoverflow.com/questions/27086779/initialize-uigesturerecognizer-as-part-of-property-definition-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!