Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@calebd
Created June 23, 2014 17:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calebd/6093259f63dee8dc935f to your computer and use it in GitHub Desktop.
Save calebd/6093259f63dee8dc935f to your computer and use it in GitHub Desktop.

How do you solve this? The enformement of self inside initializers gets in the way sometimes.

import UIKit
class MyView: UIView {
// I could define this as UIPanGestureRecognizer! but that feels like the wrong solution
let panGestureRecognizer: UIPanGestureRecognizer
init(frame: CGRect) {
// Can't do this here because self is not initialized yet
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGestureRecognizer")
super.init(frame: frame)
// Can't do this here because a `let` is required to be initialized before the super call
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGestureRecognizer")
}
func handlePanGestureRecognizer(gestureRecognizer: UIPanGestureRecognizer) {
}
}
@gekitz
Copy link

gekitz commented Jun 23, 2014

You could use @lazy for the property and initialise the property when you access it, no?

@keith
Copy link

keith commented Jun 24, 2014

Seems crappy but you can do this:

panGestureRecognizer = UIPanGestureRecognizer(target: nil, action: "handlePanGestureRecognizer")
OR
panGestureRecognizer = UIPanGestureRecognizer()

And then actually assign it after the super call

@waltflanagan
Copy link

Its arguable that you're conflating the duties of the view with that of the view controller and swift is trying to enforce that at compile time. Given that in theory views shouldn't know much about anything other than displaying content, the correct answer may be that the configuration of the gesture recognizer should happen externally and passed into the view, if indeed the view should be responsible for it going forward.

I don't believe the other solutions will help as I think initWithTarget with a nil parameter throws an exception and @lazy would require the gesture recognizer property to be accessed rather just being set up on the view.

my 2c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment