swift 在iOS 13黑暗模式下发出cgColor切换

vxf3dgd4  于 2023-08-02  发布在  Swift
关注(0)|答案(5)|浏览(188)

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

字符串

ejk8hzay

ejk8hzay1#

对于cgColor,您需要使用

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

字符串

omvjsjqw

omvjsjqw2#

当您更改模式时,将调用traitCollectionDidChange

class YourView: UIView {

  override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)

    self.layer.shadowColor = yourUIColor.cgColor
  }

}

字符串

q3qa4bjr

q3qa4bjr3#

我也有同样的问题。我通过移除子层,重新创建它并添加具有所需颜色的新子层来解决这个问题。它适用于iOS13和iOS14。

m2xkgtsf

m2xkgtsf4#

较低级别的类(如CA Layer和CG Color)不理解动态颜色。这是一个UIKit概念。
参考:https://developer.apple.com/videos/play/wwdc2019/214/?time=1415
对于UIView,我花了很多时间去弄清楚;因此,我用以下方式解决问题

override open func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        guard traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) else { return }
        customizeUpdateLayers()
    }
    func customizeUpdateLayers() {
        // do sth
    }

字符串
对于NSView,将该代码移到视图的updateLayer()方法中...
参考:https://developer.apple.com/documentation/uikit/appearance_customization/supporting_dark_mode_in_your_interface#2993898
参考:func updateLayer

bakd9h0s

bakd9h0s5#

您的所有应用程序与一行解决方案在这里,
只要你把这行放在appDelegate文件中

if #available(iOS 13.0, *) {
    window?.overrideUserInterfaceStyle = .light
}

字符串

.你可以这样添加info.plist

<key>UIUserInterfaceStyle</key>
<string>Light</string>

相关问题