我得到的错误
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[App.DetailController tap]: unrecognized selector sent to instance 0x109803800'
我的名为“DetailController”的 View Controller 有一个小的 imageView,当用户单击图像时,我希望图像放大到全屏,然后再次单击时返回到全屏之前的默认图像大小。
问题是当点击 imageView 时我的应用程序崩溃了。
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)
}
最佳答案
不要使用 Selector()
。使用 #selector()
形式。编译器能够检查具有该形式的匹配方法。
对于手势识别器,选择器应该有 1 个参数:手势识别器本身:
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tap(_:)))
你的函数看起来像这样
@IBAction func tap(_ gesutureRecognizer: UITapGestureRecognizer) {
}
对于 UIViewController
的函数,您不需要在函数上使用 @objc
限定符,因为 UIViewController
是一个 Objective- C 对象。
关于ios - Swift:尝试使用点击手势时出现 "Unrecognized selector sent to instance"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46506797/