Swift:为 UIView 添加手势识别器 class
Swift: addGestureRecognizer for UIView class
我使用这个代码:
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:]: unrecognized selector sent to class
0x10ef5cac0 2018-07-10 11:11:50.513392+0430 Ma[23098:89853] *
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '+[Ma.StarClass
handleStarWithSender:]: unrecognized selector sent to class
0x10ef5cac0'
* First throw call stack:...
线路似乎有问题:
nW.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleStar(sender:))))
这里,在 class
函数中,self
指的是 Class 类型,而不是它的对象。但是您要在对象上添加手势识别器。这里的解决方案是这样做:
nW.addGestureRecognizer(UITapGestureRecognizer(target: nW, action: #selector(handleStar(sender:))))
我使用这个代码:
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:]: unrecognized selector sent to class 0x10ef5cac0 2018-07-10 11:11:50.513392+0430 Ma[23098:89853] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[Ma.StarClass handleStarWithSender:]: unrecognized selector sent to class 0x10ef5cac0' * First throw call stack:...
线路似乎有问题:
nW.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleStar(sender:))))
这里,在 class
函数中,self
指的是 Class 类型,而不是它的对象。但是您要在对象上添加手势识别器。这里的解决方案是这样做:
nW.addGestureRecognizer(UITapGestureRecognizer(target: nW, action: #selector(handleStar(sender:))))