码迷,mamicode.com
首页 > 移动开发 > 详细

iOS swift objc_setAssociatedObject和objc_getAssociatedObject使用

时间:2018-10-25 19:41:56      阅读:450      评论:0      收藏:0      [点我收藏+]

标签:add   objc   obj   manage   cto   let   pattern   void   unsafe   

oc中的AssociationsManager在swift中也是可以实现的 使用方法请看下面一个例子

import UIKit

extension UIButton {
    
    func fk_addAction(FKActionBlock:((UIButton)->Void)?){
        //保存block
        let key : UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: "fk_addAction:".hashValue)
        objc_setAssociatedObject(self, key, FKActionBlock, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        addTarget(self, action: #selector(itemClick(button:)), for:.touchUpInside)
    }
    
    func fk_addAction(FKActionBlock:((UIButton)->Void)? ,for event:Event){
        //保存block
        let key : UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: "fk_addAction:".hashValue)
        objc_setAssociatedObject(self, key, FKActionBlock, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        addTarget(self, action: #selector(itemClick(button:)), for:event)
        
    }
    
    @objc private func itemClick(button:UIButton){
        let key : UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: "fk_addAction:".hashValue)
        objc_getAssociatedObject(self, key)
        if let fkBlock = objc_getAssociatedObject(self, key) as? ((UIButton)->Void){
            fkBlock(button)
        }
    }
}

这里是给UIButton添加一个分类,在分类中给UIButton拓展快速添加点击事件的方法通过block回传,通过objc_setAssociatedObject将block保存,触发点击事件后,通过objc_getAssociatedObject获取之前保存的block发起回调

iOS swift objc_setAssociatedObject和objc_getAssociatedObject使用

标签:add   objc   obj   manage   cto   let   pattern   void   unsafe   

原文地址:https://www.cnblogs.com/qqcc1388/p/9851663.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!