Hooking up UIButton to closure? (Swift, target-action)

前端 未结 8 1824
滥情空心
滥情空心 2020-12-13 02:51

I want to hook up a UIButton to a piece of code – from what I have found, the preferred method to do this in Swift is still to use the addTarget(target: AnyObject?, ac

8条回答
  •  醉话见心
    2020-12-13 02:59

    The associatedObject and wrapping and pointers and import of ObjectiveC are unnecessary, at least in Swift 3. This works great and is much more Swift-y. Feel free to throw a typealias in there for () -> () if you find it more readable, bit I find it easier to read the block signature directly.

    import UIKit
    
    class BlockButton: UIButton {
        fileprivate var onAction: (() -> ())?
    
        func addClosure(_ closure: @escaping () -> (), for control: UIControlEvents) {
            self.addTarget(self, action: #selector(actionHandler), for: control)
            self.onAction = closure
        }
    
        dynamic fileprivate func actionHandler() {
            onAction?()
        }
    } 
    

提交回复
热议问题