LoginSignup
8
3

More than 5 years have passed since last update.

【Swift】BlockからSelectorを作る メモ(要検証)

Posted at

コード

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!!

参考

BlockからSelector(メソッド)を作る

8
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3