swift swizzling property 交换系统属性

举例:交换 UINavigationBar 的系统属性 titleTextAttributes

let needSwizzleSelectorArr = [
    // 这里我们要交换的是属性 titleTextAttributes 的 setter 方法
    #selector(setter: titleTextAttributes)
]

for selector in needSwizzleSelectorArr {
    let str = ("wr_" + selector.description)
    let originalMethod = class_getInstanceMethod(self, selector)
    let swizzledMethod = class_getInstanceMethod(self, Selector(str))
    method_exchangeImplementations(originalMethod, swizzledMethod)
}

交换的方法

func wr_setTitleTextAttributes(_ newTitleTextAttributes:[String : Any]?)
{
    guard var attributes = newTitleTextAttributes else {
        return
    }
    
    guard let originTitleTextAttributes = titleTextAttributes else {
        wr_setTitleTextAttributes(attributes)
        return
    }
    
    var titleColor:UIColor?
    for attribute in originTitleTextAttributes {
        if attribute.key == NSForegroundColorAttributeName {
            titleColor = attribute.value as? UIColor
            break
        }
    }
    
    guard let originTitleColor = titleColor else {
        wr_setTitleTextAttributes(attributes)
        return
    }

    if attributes[NSForegroundColorAttributeName] == nil {
        attributes.updateValue(originTitleColor, forKey: NSForegroundColorAttributeName)
    }
    wr_setTitleTextAttributes(attributes)
}


强烈推荐:超简单!!! iOS设置状态栏、导航栏按钮、标题、颜色、透明度,偏移等

https://github.com/wangrui460/WRNavigationBar
https://github.com/wangrui460/WRNavigationBar_swift



欢迎关注我的微博:wangrui460

你可能感兴趣的:(swift swizzling property 交换系统属性)