Search code examples
swiftuigesturerecognizeruipinchgesturerecognizer

Swift 2: Selector in UIPinchGestureRecognizer: How to access func from another class


I'm following this class on Swift and building apps.

At 43:30 in the video, the instructor teaches how to set up a UIPinchGestureRecognizer, which takes in a function from another file in its Selector.
This is the code the instructor uses:

@IBOutlet weak var faceView: FaceView! {
        didSet {
            faceView.addGestureRecognizer(UIPinchGestureRecognizer(target: faceView, action: #selector(FaceView.changeScale(_:))))
            updateUI()
        }
    }

I get 2 errors:

Expected expression in list of expressions,

and:

Expected ',' separator.

I have tried changing #selector to Selector with no luck.

the function changeScale:

func changeScale(recognizer: UIPinchGestureRecognizer)
    {
        switch recognizer.state {
        case .Changed, .Ended:
            scale *= recognizer.scale //scale is the displayed image scale
            recognizer.scale = 1.0
        default:
            break
        }

If I surround the Selector argument with quotes, the app crashes when I pinch, giving the following error:

unrecognized selector sent to instance.


Solution

  • As can be seen in the comments above, the Xcode version is 7.2 and the #selector syntax was introduced in Xcode 7.3 and therefore not available here. This just means that you should be able to use the "old" Selector syntax.

    The difference is that you just give pass a strings to the Selector with the name of your function and then a : for each of the parameters your function requires. You require one parameter (the recognizer) so in your case the string looks like this:

    "changeScale:"
    

    So you'd use:

    Selector("changeScale:")
    

    And you end up with:

        @IBOutlet weak var faceView: FaceView! {
        didSet {
                faceView.addGestureRecognizer(UIPinchGestureRecognizer(target: faceView, action: Selector("changeScale:")))
            }
        }
    

    As you can see, this is error prone...one typo and kaboom! Which is why the new #selector syntax is a fine improvement...sorry...not trying to rub it in.

    Hope this helps you.