在iOS 13中更改模式时,我在切换颜色时遇到麻烦。
问题是您在最近的应用程序中看到该应用程序。 UIColors会更改,但cgColor不会更改。
当您打开应用程序时,它将有效地改变,但是在最近它不会改变。
我正在使用下面的苹果文档中提到的“ traitCollectionDidChange”方法。https://developer.apple.com/documentation/xcode/supporting_dark_mode_in_your_interface
[请观看视频以更清楚地了解]https://www.youtube.com/watch?v=C-pcVuPMQ9U&feature=youtu.be
class ViewController: UIViewController {
@IBOutlet weak var viewColor: UIView!
let layerColor = CALayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setLayer()
setColors()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
setColors()
}
}
func setColors() {
layerColor.backgroundColor = UIColor(named: "layerColor")?.cgColor
}
func setLayer() {
layerColor.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
viewColor.layer.addSublayer(layerColor)
}
}
问题是这种方法
func setColors() {
layerColor.backgroundColor = UIColor(named: "layerColor")?.cgColor
}
...不会导致UIColor检查当前特征集以了解我们现在是处于暗模式还是亮模式。更改为:
func setColors() {
UITraitCollection.current = self.traitCollection
layerColor.backgroundColor = UIColor(named: "layerColor")?.cgColor
}
对于cgColor,您需要使用
layerColor.backgroundColor = UIColor(named: "layerColor")?.resolvedColor(with: self.traitCollection).cgColor