How can I change a SwiftUI Color to UIColor?

后端 未结 5 987
醉酒成梦
醉酒成梦 2021-01-07 17:02

I\'m trying to change a SwiftUI Color to an instance of UIColor.

I can easily get the RGBA from the UIColor, but I don\'t know how to get the "Color" instan

5条回答
  •  渐次进展
    2021-01-07 17:27

    How about this solution?

    extension Color {
     
        func uiColor() -> UIColor {
    
            if #available(iOS 14.0, *) {
                return UIColor(self)
            }
    
            let components = self.components()
            return UIColor(red: components.r, green: components.g, blue: components.b, alpha: components.a)
        }
    
        private func components() -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) {
    
            let scanner = Scanner(string: self.description.trimmingCharacters(in: CharacterSet.alphanumerics.inverted))
            var hexNumber: UInt64 = 0
            var r: CGFloat = 0.0, g: CGFloat = 0.0, b: CGFloat = 0.0, a: CGFloat = 0.0
    
            let result = scanner.scanHexInt64(&hexNumber)
            if result {
                r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
                g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
                b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
                a = CGFloat(hexNumber & 0x000000ff) / 255
            }
            return (r, g, b, a)
        }
    }
    

    Usage:

    let uiColor = myColor.uiColor()
    

    It's a bit of a hack, but it's at least something until we get a valid method for this. The key here is self.description which gives a hexadecimal description of the color (if it's not dynamic I should add). And the rest is just calculations to get the color components, and create a UIColor.

提交回复
热议问题