简体   繁体   中英

Button border color will not change to custom color

I have a very simple transparent button subclass, and I am trying to change the border to be the same color as the text, however it turns out white.

class transparentButton: UIButton {

    required init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
        setupButton()
    }
    
    // Setup the button
    func setupButton() {
        self.backgroundColor = .clear
        self.layer.borderWidth = 3
        self.layer.borderColor = CGColor(red: 203, green: 72, blue: 75, alpha: 0.75)
    }
    

}

The CGColor init takes in values from 0 to 1 , as the documentation says:

CGColor init的参数,表示每个值必须在0.0 t0 1.0之间

Instead of being out of 255 as you might be used to, the maximum value is 1 . If you supply a value that is over 1 , I assume it just caps down to 1 , which means that:

CGColor(red: 203, green: 72, blue: 75, alpha: 0.75)

turns into...

CGColor(red: 1, green: 1, blue: 1, alpha: 0.75)

...which is a white color.

So, you must divide everything by 255 .

func setupButton() {
   self.backgroundColor = .clear
   self.layer.borderWidth = 3   
   self.layer.borderColor = CGColor(red: 203 / 255, green: 72 / 255, blue: 75 / 255, alpha: 0.75)
}
Before After
在此处输入图像描述 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM