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

前端 未结 8 1808
滥情空心
滥情空心 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 03:00

    According to n13's solution, I made a swift3 version.

    Hopes it could help some people like me.

    import Foundation
    import UIKit
    import ObjectiveC
    
    var ActionBlockKey: UInt8 = 0
    
    // a type for our action block closure
    typealias BlockButtonActionBlock = (_ sender: UIButton) -> Void
    
    class ActionBlockWrapper : NSObject {
        var block : BlockButtonActionBlock
        init(block: @escaping BlockButtonActionBlock) {
            self.block = block
        }
    }
    
    extension UIButton {
        func block_setAction(block: @escaping BlockButtonActionBlock, for control: UIControlEvents) {
            objc_setAssociatedObject(self, &ActionBlockKey, ActionBlockWrapper(block: block), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            self.addTarget(self, action: #selector(UIButton.block_handleAction), for: .touchUpInside)
        }
    
        func block_handleAction(sender: UIButton, for control:UIControlEvents) {
    
            let wrapper = objc_getAssociatedObject(self, &ActionBlockKey) as! ActionBlockWrapper
            wrapper.block(sender)
        }
    }
    

提交回复
热议问题