swizzle 自定义控件的 backgroundColor 方法

在 UITableViewCell 中使用 LCDefaultAvatarView的时候,发现在UITableView的默认多选状态下,如果选中cell,  那么cell中包含的 Avatar 背景会不显示,后面发现原因是 UITableView 会在选中的时候,给cell的 children view都设置 默认的 backgroundColor,  所以想到了 替换 backgroundColor的方式。

使用了 runTime 机制。

 

 

 

class LCDefaultAvatarView : UIView {
    
    private var charLabel : UILabel! = nil
    var char : Character! = nil {
        didSet {
            charLabel.text = String(char)
        }
    }
    
    var bgColor : UIColor! = nil {
        didSet {
            super.perform(#selector(setMyBackgroundColor), with: bgColor)
        }
    }
    
    override var backgroundColor: UIColor? {
        get {
            return super.backgroundColor
        }
        set {
            NSLog("set background color = %@", newValue!)
            super.backgroundColor = newValue
        }
    }
    
    static var isInit : Bool = false
    
    init() {
        super.init(frame: CGRect.zero)

        if LCDefaultAvatarView.isInit == false {
            LCDefaultAvatarView.isInit = true
            
            let originBackgroundSelector = #selector(setter: backgroundColor)
            let myBackgroundSelector = #selector(setMyBackgroundColor)
            
            let originMethod = class_getInstanceMethod(self.classForCoder, originBackgroundSelector)
            let myMethod = class_getInstanceMethod(self.classForCoder, myBackgroundSelector)
            
            method_exchangeImplementations(originMethod!, myMethod!)
        }
        
        charLabel = UILabel()
        charLabel.textAlignment = NSTextAlignment.center
        charLabel.font = UIFont.systemFont(ofSize: 24.0)
        charLabel.textColor = UIColor.white
        self.addSubview(charLabel)
        charLabel.setAutoLayoutFillParent()
    }
    
    
    @objc func setMyBackgroundColor(color : UIColor?) {
        NSLog("setMyBackgroundColor ")
    }
    
 
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

 

你可能感兴趣的:(iphone/object-c,Swift)