How can I create a UIColor from a hex string?

后端 未结 30 1715
北恋
北恋 2020-11-22 16:53

How can I create a UIColor from a hexadecimal string format, such as #00FF00?

30条回答
  •  孤街浪徒
    2020-11-22 17:16

    You can make a extension like this

    extension UIColor{
        convenience init(rgb: UInt, alphaVal: CGFloat) {
            self.init(
                red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
                green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
                blue: CGFloat(rgb & 0x0000FF) / 255.0,
                alpha: alphaVal
            )
        }
    }
    

    And use it anywhere like this

    UIColor(rgb: 0xffffff, alphaVal: 0.2)
    

提交回复
热议问题