简体   繁体   中英

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.

I am running Xcode 8.1(8B62) and a iPhone 5 simulator on MacBook Air (Ver 100.11.6)

This is the code I used that works

faceView.addGestureRecognizer(UIPinchGestureRecognizer(target:faceView,

action:#selector(FaceView.changeScale(recognizer:))))

When you pinch the face, make sure click "Option + Left Click + Movement on your mousepad". I make the mistake of just pressing "Option + Movement on the mousepad" and it does not work.

Hope it helps.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM