美文网首页
didSet willSet在init里面没有作用

didSet willSet在init里面没有作用

作者: Doublingli | 来源:发表于2017-01-05 02:58 被阅读0次

    今天修改了这个按钮类,用来在运行时根据数据来调整按钮的颜色和文字,修改后初始化的时候发现颜色和文字都没有设置,经研究和查证,在initializer内对变量进行初始化赋值是不会掉用didSet和willSet的~

    class PopupButton : UIButton {
      
        let defaultHeight:CGFloat = 44
        let margin:CGFloat = 8
        let cornerRadius:CGFloat = 4
        
        var title:String! {
            didSet {
                if let t = title {
                    self.updateTitle(title: t)
                }
            }
        }
        var index:Int = 0
        var type:PopupButtonType! {
            didSet {
                if let t = type {
                    self.updateType(type: t)
                }
            }
        }
        
        // 在initializer中初始化变量是不会掉用didSet和willSet的
        init(title:String, buttonType:PopupButtonType = PopupButtonType.normal) {
            super.init(frame:CGRect(x: 0, y: 8, width: UIScreen.main.bounds.width - margin*2, height: defaultHeight))
            // didSet willSet 不会在init里面调用
            self.title = title        // 这里set后不会掉用didSet方法
            self.updateTitle(title: title)    // 这里必须调用updateTitle 
            self.type = buttonType    // 这里set后不会掉用didSet方法
            self.updateType(type: buttonType)  //这里必须调用updateType 
            self.alpha = 1
            self.layer.cornerRadius = cornerRadius
            self.layer.masksToBounds = true
            self.setBackgroundImage(AtColor.backgroundLight().getImage(), for: UIControlState.highlighted)
            self.setBackgroundImage(AtColor.white().getImage(), for: UIControlState())
        }
        
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
        
        fileprivate func updateTitle(title:String) {
            DispatchQueue.main.async {
                self.setTitle(self.title, for: UIControlState())
            }
        }
        
        fileprivate func updateType(type:PopupButtonType) {
            DispatchQueue.main.async {
                switch type {
                case PopupButtonType.normal:
                    self.setTitleColor(atColor: AtColor.normalBlue(), forState: UIControlState())
                case PopupButtonType.warning:
                    self.setTitleColor(atColor: AtColor.iconRed(), forState: UIControlState())
                case PopupButtonType.disabled:
                    self.setTitleColor(atColor: AtColor.textLightGray(), forState: UIControlState())
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:didSet willSet在init里面没有作用

          本文链接:https://www.haomeiwen.com/subject/cnwavttx.html