Extension-Selector
在Swift中,我们可以使用#selector设置target-action模式中的action操作,如下代码所示:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: .custom)
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
view.addSubview(button)
}
func buttonTapped() {
}
}
如果你有代码洁癖,想把#selector集中起来管理,则可以定义一个结构体,来统一归集这样的代码,如下图所示。这样看着是不是会更整洁一些?

不过,还有种更好的方式,就是直接扩展Selector结构体,如下代码所示,这样可以在使用时直接用.buttonTapped这种方式来引用,就像我们使用.red这样的UIColor属性一样简洁。
extension Selector {
static let buttonTapped = #selector(ViewController.buttonTapped)
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: .custom)
button.addTarget(self, action: .buttonTapped, for: .touchUpInside)
view.addSubview(button)
}
func buttonTapped() {
}
}
参考