UIButton block equivalent to addTarget:action:forControlEvents: method?

后端 未结 9 1206
旧巷少年郎
旧巷少年郎 2020-11-29 20:58

I looked around, but couldn\'t find this on the internet, nor anywhere in the Apple docs, so I\'m guessing it doesn\'t exist.

But is there a iOS4 blocks equivalent A

9条回答
  •  萌比男神i
    2020-11-29 21:29

    Swift 4

    Here is the swift solution

    class ClosureSleeve {
    let closure: () -> ()
    
    init(attachTo: AnyObject, closure: @escaping () -> ()) {
        self.closure = closure
        objc_setAssociatedObject(attachTo, "[\(arc4random())]", self, .OBJC_ASSOCIATION_RETAIN)
    }
    
    @objc func invoke() {
        closure()
      }
    }
    
    extension UIControl {
    func addAction(for controlEvents: UIControlEvents = .primaryActionTriggered, action: @escaping () -> ()) {
        let sleeve = ClosureSleeve(attachTo: self, closure: action)
        addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
     }
    }
    

    Example Usage:

    button.addAction {
    print("button pressed")
    }
    

提交回复
热议问题