【发布时间】:2019-01-05 11:14:10
【问题描述】:
在 Swift 中有什么方法可以在整个应用程序中一次更改我的 UILabel 的文本颜色属性吗?我尝试过使用外观属性,但这不适用于 UILabel textColor。任何方式或任何库都可以使用。
【问题讨论】:
-
使用
appearance仅适用于新创建的标签,不适用于现有标签。
在 Swift 中有什么方法可以在整个应用程序中一次更改我的 UILabel 的文本颜色属性吗?我尝试过使用外观属性,但这不适用于 UILabel textColor。任何方式或任何库都可以使用。
【问题讨论】:
appearance 仅适用于新创建的标签,不适用于现有标签。
【讨论】:
UILabels 的确切解决方案。因为他必须为每个标签重新设置颜色
UIButton 或UIBarButtonItem 这样的元素的文本颜色取决于属性tintColor,因为您可以设置全局色调,所有“突出显示”的元素都将具有这种颜色。我认为这不是更改所有标签颜色的好方法,因为标签可以在各种情况下使用。然后,我认为使用 Color Set 很好
UILabels 的文本颜色。
在 AppDelegate.swift 内的 didFinishLaunchingWithOptions 函数中试试这个:
UILabel.appearance(whenContainedInInstancesOf: [UIView.self]).textColor = .red //or what color you want
【讨论】:
我真的很喜欢Arash Etemad's solution,但发现它非常极端,因为它超越了所有颜色,即使其中一些是定制的。在处理现有的大型项目时,这并不是很好。
所以我想出了这个(Swift 5.2):
extension UILabel {
override open func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
guard newSuperview != nil else {
return
}
if #available(iOS 13.0, *) {
if textColor == UIColor.label {
textColor = .red
}
} else if textColor == UIColor.darkText {
textColor = .red
}
}
}
它使用标签自己的生命周期事件来覆盖默认的系统字体颜色。随着 iOS 13 中暗模式的出现,可以识别为UIColor.label,而之前是UIColor.darkText。
这可以防止自定义字体颜色被覆盖(除非您的自定义颜色与默认颜色相同 ?!? ),同时不需要在整个项目中手动设置字体颜色。
【讨论】:
UILabel设置默认颜色,然后你可以有一些不同颜色的自定义标签!
didFinishLaunching 中应用的解决方案导致所有内容都更改为该颜色,即使 95% 已经设置了自定义颜色。我想可以更新颜色设置的方式,使其工作,但是你会转换 95% 的代码库,用于损坏的 5%。但我肯定更喜欢你在一个新项目上的解决方案,那里没有太多的遗留问题,而且当它可以从一开始就遵循时,这是一个很好的模式。
创建一个 UILabel 类并将该类中的 textColour 设置为您想要的颜色。并将此类用于您在应用程序中使用的所有标签。如果您想在会话期间更改所有标签的颜色,例如通过按钮操作,您可以使用 NotificationCenter 和 Singleton。
class LabelColor {
static let shared = LabelColor()
var color = UIColor.red
}
class ColoredLabel: UILabel {
override func awakeFromNib() {
super.awakeFromNib()
textColor = LabelColor.shared.color
NotificationCenter.default.addObserver(self, selector: #selector(self.changeColor(notification:)), name: Notification.Name(rawValue: "ChangeColor"), object: nil)
}
@objc func changeColor(notification: Notification) {
let newColor = UIColor.blue
textColor = newColor
LabelColor.shared.color = newColor
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func changeColour(_ sender: UIButton) {
NotificationCenter.default.post(name: Notification.Name("ChangeColor"), object: nil)
}
}
【讨论】: