xcode 所有 UILabels 的默认文本颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41278153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The default text color for all UILabels
提问by Adrian Bobrowski
I want to set the default text color for all UILabels in my app. I found this:
我想为我的应用程序中的所有 UILabel 设置默认文本颜色。我找到了这个:
UILabel.appearance().textColor = UIColor.red
This works, but when I want to set some other color for a particular label in its storyboard, it cannot be done - all labels are still red.
这有效,但是当我想为其故事板中的特定标签设置其他颜色时,无法完成 - 所有标签仍然是红色。
Is it possible to define a default text color for all UILabels by setting it in storyboards and then change it for some UILabels ALSO in storyboards (not in code)? Or set the default color in code using the Appearance API and change it for some labels in storyboard?
是否可以通过在情节提要中设置所有 UILabel 来定义默认文本颜色,然后在情节提要中(而不是在代码中)为某些 UILabel 更改它?或者使用 Appearance API 在代码中设置默认颜色并为故事板中的某些标签更改它?
采纳答案by Muhammad Adnan
SubClass you labels with CustomLabel.swift. You can set text color using IBDesignable
property named as txtColor
使用 CustomLabel.swift 对您的标签进行子类化。您可以使用IBDesignable
名为的属性设置文本颜色txtColor
Below is the code working example
下面是代码工作示例
import UIKit
@IBDesignable class CustomLabel: UILabel {
@IBInspectable var txtColor: UIColor = UIColor.grayColor() {
didSet {
self.textColor = txtColor
}
}
func setup() {
self.textColor = txtColor
}
override func awakeFromNib() {
setup()
}
override func prepareForInterfaceBuilder() {
setup()
}
}
回答by Lefteris
There is also an alternative to what Muhammad suggested. The alternative is to use the UIAppearance proxy, but specify the classes where it would be applied to.
除了穆罕默德的建议之外,还有一个替代方案。另一种方法是使用 UIAppearance 代理,但指定将应用到的类。
In that case, you would use it like this:
在这种情况下,您可以这样使用它:
UILabel.appearanceWhenContainedInInstancesOfClasses([MyViewController.self, MyotherViewController.self]).textColor = UIColor.red
The above though, would only allow you to set the textColor your self in some classes. in those where the proxy is set to be enabled, you won't be able to set the text color.
但是,上面只允许您在某些类中设置自己的 textColor 。在那些设置为启用代理的情况下,您将无法设置文本颜色。
It's up to you to choose which approach is better for your case
您可以选择哪种方法更适合您的情况