在UIView Extension中实现时,无法将操作添加到UIView。
UIView扩展
extension UIView {
public func addAction(_ selector: Selector) {
isUserInteractionEnabled = true
let gesture = UITapGestureRecognizer(target: self, action: selector)
self.addGestureRecognizer(gesture)
}
}ViewController中的In函数
func setAction(_ button: UIView, _ selector: Selector?) {
button.isUserInteractionEnabled = true
let gesture = UITapGestureRecognizer(target: self, action: selector)
button.addGestureRecognizer(gesture)
}
@objc func hello(){
print("Hello")
}我有一个名为menu的UIView控制器,当我按下它时,我想让它打印出"Hello“。
如果我执行方法1,我会得到一个错误。
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView hello:]: unrecognized selector sent to instance 0x11fd4ca30'如果我使用方法2,它工作得很好。
1- menu.addAction(#selector(hello))
2- setAction(menu, #selector(hello))
但我可能会经常用到这个。如何通过扩展将操作添加到UIView?
发布于 2021-11-10 05:56:12
在扩展磁带手势中,在UIView类中找不到hello方法。
extension UIView {
public func addAction(_ selector: Selector, target: AnyObject) {
isUserInteractionEnabled = true
let gesture = UITapGestureRecognizer(target: target, action: selector)
self.addGestureRecognizer(gesture)
}
}在addAction方法中为操作的目标添加一个参数。
https://stackoverflow.com/questions/69908442
复制相似问题