我使用以下代码:
class StarClass: UIView {
@IBOutlet weak var bgStar: UIView!
class func createMyClassView() -> StarClass {
let myClassNib = UINib(nibName: "Star", bundle: nil)
let nW = myClassNib.instantiate(withOwner: nil, options: nil)[0] as! StarClass
nW.bgStar.layer.cornerRadius = 15
nW.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleStar(sender:))))
return nW
}
@objc func handleStar(sender: UITapGestureRecognizer) {
print("iosLog STAR")
}
}
运行后,如果单击该视图,则会在下面显示错误:
2018-07-10 11:11:50.496349 + 0430 Ma [23098:89853] + [Ma.StarClass handleStarWithSender:]:无法识别的选择器已发送给类 0x10ef5cac0 2018-07-10 11:11:50.513392 + 0430 Ma [23098:89853] * 由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:'+ [Ma.StarClass handleStarWithSender:]:无法识别的选择器已发送给类 0x10ef5cac0' * 第一个调用堆栈:...
答案 0 :(得分:1)
该行似乎有问题:
nW.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleStar(sender:))))
在class
函数内部,self
引用的是Class类型,而不是其对象。但是,您要在对象上添加手势识别器。解决方案是执行此操作:
nW.addGestureRecognizer(UITapGestureRecognizer(target: nW, action: #selector(handleStar(sender:))))