繁体   English   中英

SwiftUI:使用资产目录中的颜色集

[英]SwiftUI: Using Color Set from Asset Catalog

在 SwiftUI 中,我们可以使用以下命令从资产目录中的颜色集中获取颜色:

extension Color {
    static let coral = Color("coral")
}

这需要字符串类型的名称,并且对于许多颜色集变得非常乏味。 是否有另一种获取颜色集的方法,类似于我们使用图像文字从资产目录中获取图像的方式? 或者,只是一些不那么多余的东西。

如果不是,如何在 SwiftUI 中以编程方式创建动态颜色? 例如,这就是它在 UIKit 中的完成方式:

extension UIColor {
    static let dynamicColor = UIColor { $0.userInterfaceStyle == .dark ? .black : .white }
}

我想分享一种在资产目录中定义动态颜色的替代方法,但不需要编写繁琐的代码

Color("yellow")

1. 像往常一样在资产目录中定义你的颜色

在此处输入图像描述

2. 在您的代码中,找到一个将您的颜色定义为变量的位置,在我的情况下,它将是这样的:

extension Color {
    static let ui = Color.UI()
    
    struct UI {
         let yellow = Color("yellow")
    }
}

3. 完成

像这样使用你的颜色:

Text("Hello").background(Color.ui.yellow)

这只需要在代码中编写硬编码颜色 1 次。

如果不是,如何在 SwiftUI 中以编程方式创建动态颜色? 例如,这就是它在 UIKit 中的完成方式:

这几乎是一样的:

extension Color {
    static let dynamicColor = Color(UIColor { traitCollection in
        return traitCollection.userInterfaceStyle == .dark ? .black : .white
    })
}

备份

将扩展添加到Color是最简单的

extension Color {
    static let primary = Color("Primary")
    static let secondary = Color("Secondary")
}

然后它很容易使用

Text("My Primary Color")
     .foregroundColor(.primary)

如果您需要将其用作UIColor ,则在 UIColor 上进行扩展并将实现更改为

Text("My Primary UIColor")
     .foregroundColor(Color(uiColor: .primary))

我很确定苹果会把这个留给开发者。 例如,您可以为 SwiftUI 颜色编写自定义SwiftGen (或稍等)模板。 https://github.com/SwiftGen/SwiftGen#colors

这是另一种方法:

import SwiftUI

enum AssetsColor : String
{
    case assetColorA
    case assetColorB
}

extension Color
{
    static func uiColor(_ name: AssetsColor) -> Color
    {
        return Color(name.rawValue)
    }
}

...

.backgroundColor(Color.uiColor(.assetColorA))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM