在SwiftUI中使用十六进制颜色 [英] Use Hex color in SwiftUI

查看:684
本文介绍了在SwiftUI中使用十六进制颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在UIKit中,我们可以使用扩展将十六进制颜色设置为几乎所有内容. https://www .hackingwithswift.com/example-code/uicolor/how-to-convert-a-hex-color-to-a-uicolor

in UIKit we could use an Extension to set hex color to almost everything. https://www.hackingwithswift.com/example-code/uicolor/how-to-convert-a-hex-color-to-a-uicolor

但是当我尝试在SwiftUI上执行此操作时,这是不可能的,看起来SwiftUI没有将UIColor作为参数.

but when I'm trying to do it on SwiftUI, it's not possible, it looks like the SwiftUI does not get the UIColor as parameter.

    Text(text)
        .color(UIColor.init(hex: "FFF"))

错误消息:

Cannot convert value of type 'UIColor' to expected argument type 'Color?'

我什至尝试扩展Color而不是UIColor,但是我没有运气

I even tried to make an extension for Color, instead of UIColor, but I haven't any luck

我的颜色扩展名:

导入SwiftUI

extension Color {
    init(hex: String) {
        let scanner = Scanner(string: hex)
        scanner.scanLocation = 0
        var rgbValue: UInt64 = 0
        scanner.scanHexInt64(&rgbValue)

        let r = (rgbValue & 0xff0000) >> 16
        let g = (rgbValue & 0xff00) >> 8
        let b = rgbValue & 0xff

        self.init(
            red: CGFloat(r) / 0xff,
            green: CGFloat(g) / 0xff,
            blue: CGFloat(b) / 0xff, alpha: 1
        )
    }
}

错误消息:

Incorrect argument labels in call (have 'red:green:blue:alpha:', expected '_:red:green:blue:opacity:')

推荐答案

您快到了,您使用了错误的初始化程序参数:

You're almost there, you were using the wrong initialiser parameter:

extension Color {
    init(hex: String) {
        let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
        var int: UInt64 = 0
        Scanner(string: hex).scanHexInt64(&int)
        let a, r, g, b: UInt64
        switch hex.count {
        case 3: // RGB (12-bit)
            (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
        case 6: // RGB (24-bit)
            (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
        case 8: // ARGB (32-bit)
            (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
        default:
            (a, r, g, b) = (1, 1, 1, 0)
        }

        self.init(
            .sRGB,
            red: Double(r) / 255,
            green: Double(g) / 255,
            blue:  Double(b) / 255,
            opacity: Double(a) / 255
        )
    }
}

这篇关于在SwiftUI中使用十六进制颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆