首页 > 解决方案 > 在 iOS 13 深色模式下问题 cgColor 切换

问题描述

在 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)
    }
}

标签: iosswiftcalayeruibezierpathcgcolor

解决方案


对于 cgColor 你需要使用

layerColor.backgroundColor = UIColor(named: "layerColor")?.resolvedColor(with: self.traitCollection).cgColor

推荐阅读