以编程方式定义颜色并在 Interface Builder 中使用它们

Defining colours programmatically and using them in Interface Builder

我想自定义应用程序的颜色,重复使用相同的元素但改变颜色。

这些元素是简单的 Views、UIButton、UILabel 等,没什么特别的。颜色可能来自 XML 或 plist,我将预加载并解析为 UIColor。

是的,我可以从它们中的每一个创建一个出口并手动设置它们,但我有数百个元素,我想避免这条路。

我尝试了 IBInspectable,没有运气,我正在寻找一个广泛的解决方案,所有视图,所有 VC。

顺便说一下,我正在 Objective-C 编码...

你能建议我该怎么做吗?

如果您需要更多详细信息,请发表评论……

非常感谢大家!

情侣选项...

  1. 子类化您的 UI 元素,并使用 MYUIButton 而不是 UIButton,例如,或

  2. 查看UI外观代理 - https://developer.apple.com/reference/uikit/uiappearance - 使用它,您可以为整个应用程序设置默认外观特征。

示例:

[[UIButton appearance] setBackgroundColor:[UIColor yellowColor]];
[[UILabel appearance] setBackgroundColor:[UIColor orangeColor]];

如果您包含这两行(通常在 AppDelegate / didFinishLaunchingWithOptions 中完成),您应用中的 every UIButton 将具有黄色背景,并且 每个 UILabel 都有橙色背景。

(但是,您不会在 Interface Builder 中看到这些更改)


编辑:

正如 Charles 在他的评论中提到的那样,您可以创建子 类,然后仅将外观更改应用于那些 类。

假设您有 3 个按钮 "types",您想要将 "color scheme" 应用到 - 深蓝色、中蓝色、浅蓝色或深红色、中红色、浅-红色等。您可以采用创建 DarkUIButton、MediumUIButton 和 LightUIButton sub类 的方法。然后,当您加载配色方案时...

[[DarkUIButton appearance] setBackgroundColor:scheme.darkcolor];
[[MediumUIButton appearance] setBackgroundColor:scheme.mediumcolor];
[[LightUIButton appearance] setBackgroundColor:scheme.lightcolor];