gpt4 book ai didi

Swift:为 UIView 类添加手势识别器

转载 作者:行者123 更新时间:2023-11-28 14:31:06 25 4
gpt4 key购买 nike

我使用这段代码:

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")
}
}

运行后,如果我点击 View ,会出现以下错误:

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:))))

关于Swift:为 UIView 类添加手势识别器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51258784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com