ios - 在 SwiftUI 中使用十六进制颜色

标签 ios swift swiftui uicolor

在 UIKit 中,我们可以使用扩展来为几乎所有内容设置十六进制颜色,就像这个 tutorial .但是当我尝试在 SwiftUI 中执行此操作时,这是不可能的,看起来 SwiftUI 没有将 UIColor 作为参数。

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

错误信息:

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

我什至试图为 Color 做一个扩展,而不是 UIColor,但我没有任何运气。

我的 Color 扩展:

import 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:')

最佳答案

你快到了,你使用了错误的初始化参数:

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
        )
    }
}

关于ios - 在 SwiftUI 中使用十六进制颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56874133/

相关文章:

ios - 如何将数据(从服务器获取)传递到 UIView 中的 tableView

ios - UIScrollerView 内的 UIView 以 -64 偏移量显示

ios - “流在打开之前正在发送事件”

ios7 - 访问数组使 UITableView 在滚动时滞后

ios - SwiftUI:从单元格 View 中删除托管对象会使应用程序崩溃[非可选属性]?

ios - NavigationLink 似乎只占用一点空间

ios - 将字符串日期转换为 NSDate 的问题

ios - 带有 IB_DESIGNABLE 的 UIButton 会引发运行时属性警告,并且不会在 Interface Builder 中呈现

Swift 2/iOS 9 - 找不到 libz.dylib

swiftui - Xcode beta中的NavigationStack的navigationDestination无法导航