Swift: "Unrecognized selector sent to instance" 尝试使用点击手势时出错
Swift: "Unrecognized selector sent to instance" error when trying to use tap gesture
我遇到的错误
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[App.DetailController tap]: unrecognized selector sent to instance 0x109803800'
我的名为 'DetailController' 的视图控制器有一个小的 imageView,当用户单击图像时,我希望图像放大到全屏,然后再次单击时 return 到默认图像全屏之前的大小。
问题是单击 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 对象。
我遇到的错误
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[App.DetailController tap]: unrecognized selector sent to instance 0x109803800'
我的名为 'DetailController' 的视图控制器有一个小的 imageView,当用户单击图像时,我希望图像放大到全屏,然后再次单击时 return 到默认图像全屏之前的大小。
问题是单击 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 对象。