コード
SelectorExt.swift
extension Selector {
init(_ target: AnyObject, _ methodName: String, _ block: @escaping (Void)-> Void) {
self.init(methodName)
let imp: IMP = imp_implementationWithBlock(unsafeBitCast(block as @convention(block) (Void)-> Void, to: AnyObject.self))
class_addMethod(target.classForCoder, self, imp, "v@")
}
}
使い方
ViewController.swift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: 50, height: 50)))
button.backgroundColor = .yellow
var cnt = 0
let sel = Selector(button, "didTaped") {
print("\(cnt) taped!!")
cnt+=1
}
button.addTarget(self, action: sel, for: .touchUpInside)
view.addSubview(button)
}
0 taped!!
1 taped!!
2 taped!!
3 taped!!
4 taped!!
5 taped!!
6 taped!!
7 taped!!
8 taped!!
9 taped!!