更简短的解释:
你经常想要扩展"目标"......通常是目标Any?
.但你不能扩展Any
.怎么做?
想想这个,
extension UIViewController { func add(tap v:UIView, _ action:Selector) { let t = UITapGestureRecognizer(target: self, action: action) v.addGestureRecognizer(t) } }
很好,你现在可以......
self.tap(redButton, #selector(clickedRedButton))
...在任何视图控制器中.
但你可以对任何目标做同样的事情.
所以,要在UITableViewCell上使用扩展说,你还必须拥有....
extension UIGestureRecognizerDelegate { func add(tap v:UIView, _ action:Selector) { let t = UITapGestureRecognizer(target: self, action: action) v.addGestureRecognizer(t) } }
UITapGestureRecognizer的目标参数实际上是 Any?
但是,你不能这样做......
extension Any {
解决方案是什么?如何制作一个可以在其上工作的扩展,Any?
例如在第一个参数中UITapGestureRecognizer
?
或者正如Conner'c评论所暗示的,有没有办法:
extension UIViewController or UIView {
而不是复制和粘贴两次?
每个结构/类都遵循"被动"的"任何".Any的扩展会将该功能添加到语言和代码中的每个类型.目前这是不可能的,我怀疑它是否(或应该是).
无论如何,这里有几种方法可以解决这个问题.
我的首选是添加功能的协议扩展:
protocol TapGestureAddable { func addTapGestureRecognizer(to view: UIView, with action: Selector) -> UITapGestureRecognizer } extension TapGestureAddable { func addTapGestureRecognizer(to view: UIView, with action: Selector) -> UITapGestureRecognizer { let recognizer = UITapGestureRecognizer(target: self, action: action) view.addGestureRecognizer(recognizer) return recognizer } } extension UIViewController: TapGestureAddable { } extension UIView: TapGestureAddable { }
这迫使你有意识地选择将功能添加到给定的类(IMO),而不必复制任何有意义的代码.
可能更好的选择是使这个逻辑成为UIView的扩展:
extension UIView { func addTapGestureRecognizer(with responder: Any, for action: Selector) -> UITapGestureRecognizer { let recognizer = UITapGestureRecognizer(target: responder, action: action) self.addGestureRecognizer(recognizer) return recognizer } func addTapGestureRecognizer(with action: Selector) -> UITapGestureRecognizer { let recognizer = UITapGestureRecognizer(target: self, action: action) self.addGestureRecognizer(recognizer) return recognizer } }
否则,只需创建一个全局函数:
func addTapGestureRecognizer(to view: UIView, with responder: Any, for action: Selector) -> UITapGestureRecognizer { let recognizer = UITapGestureRecognizer(target: responder, action: action) view.addGestureRecognizer(recognizer) return recognizer }