Initialize UIGestureRecognizer as part of property definition in Swift?

2.2k views Asked by At

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

There are 1 answers

1
jrturton On BEST ANSWER

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.