Swift: “Unrecognized selector sent to instance” er

2019-03-05 05:09发布

问题:

Error that I'm getting

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[App.DetailController tap]: unrecognized selector sent to instance 0x109803800'

My view controller called 'DetailController' has a small imageView and when the user clicks the image, I want the image to enlarge to full screen, then when clicked again to return to the default image size it had before the full screen.

Problem is that my app is crashing when the imageView is being clicked.

ViewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()

    iconImage.isUserInteractionEnabled = true
    let tapGesture = UITapGestureRecognizer(target: self, action: Selector(("tap")))
    iconImage.addGestureRecognizer(tapGesture)
}

func tap() {

    let screenSize: CGRect = UIScreen.main.bounds
    let screenWidth = screenSize.width
    let screenHeight = screenSize.height
    iconImage.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
}

回答1:

Don't use Selector(). Use the #selector() form. The compiler is able to check for a matching method with that form.

And for a gesture recognizer, the selector should have 1 parameter: The gesture recognizer itself:

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tap(_:)))

And your function would look like this

@IBAction func tap(_ gesutureRecognizer: UITapGestureRecognizer) {
}

For a function of a UIViewController you shouldn't need the @objc qualifier on the function, since a UIViewController is an Objective-C object.