How to I properly set UIColor from int?

后端 未结 6 857
余生分开走
余生分开走 2021-01-05 11:47

I am trying to set the textColor of a UITextView by assigning it a value.

Earlier in the program I have

textView.textColor         


        
6条回答
  •  执笔经年
    2021-01-05 12:13

    Swift version

    You can use the following function to convert a RGB hexadecimal color Int to a UIColor.

    func uiColorFromHex(rgbValue: Int) -> UIColor {
        
        // &  binary AND operator to zero out other color values
        // >>  bitwise right shift operator
        // Divide by 0xFF because UIColor takes CGFloats between 0.0 and 1.0
        
        let red =   CGFloat((rgbValue & 0xFF0000) >> 16) / 0xFF
        let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 0xFF
        let blue =  CGFloat(rgbValue & 0x0000FF) / 0xFF
        let alpha = CGFloat(1.0)
        
        return UIColor(red: red, green: green, blue: blue, alpha: alpha)
    }
    

    And can be used like this

    let myColorValue = 0x888888
    let color = uiColorFromHex(myColorValue)
    

提交回复
热议问题