Swift - 在视图控制器中使用 overrideUserInterfaceStyle 更改模式不会在 UIView 中更新 UITraitCollection.current.userInterfaceStyle

Swift - Changing modes using overrideUserInterfaceStyle in a view controller does not update UITraitCollection.current.userInterfaceStyle in a UIView

在此视图控制器中,有一个使用以下代码在明暗模式之间切换的按钮:

@IBAction func toggleModeButtonAction(_ sender: Any) {
    if let appDelegate = UIApplication.shared.delegate, let window = appDelegate.window, let unwrappedWindow = window {
        unwrappedWindow.overrideUserInterfaceStyle = traitCollection.userInterfaceStyle == .dark ? .light : .dark
    }
    ...
}

视图控制器内部有一个 mapbox 地图视图,它具有我通过图层添加的注释。当上面的函数执行时,它会清除地图和注释并重新添加它们。

问题出在这个注释视图中,当我尝试根据 userInterfaceStyle 更新背景颜色时,样式总是停留在设备系统外观(无论用户加载哪个)并且不更新。您在那里看到的打印语句只会一遍又一遍地打印出默认值。

class CustomAnnotationView: MGLAnnotationView {
    init() { ... }

    override func draw(_ rect: CGRect) {
        ...

        print("-----> \(UITraitCollection.current.userInterfaceStyle.rawValue)")
        let fillColor: UIColor = UITraitCollection.current.userInterfaceStyle == .dark ? .orange : .darkgrey

        ...
    }
}

如何获取此视图以检索 overrideUserInterfaceStyle 样式?当我添加它时,这里的 traitCollectionDidChange 函数从不执行(大概是因为注释每次都是从头开始创建的,这是有道理的)。

我之所以不只是将颜色设置为根据 userInterfaceStyle 在颜色之间变化的系统颜色,是因为我最终将此 annotationView 转换为我作为图层添加到地图中的图像。因为它是图像,所以不会更新颜色。所以我必须完全擦除地图并重新添加注释以获得正确的外观。

问题源于 UIView 在我初始化它时没有父级,因此它无处可读 traitCollection 并退回到使用系统设置。解决方法是从 viewController 传入 userInterfaceStyle 并在 CustomAnnotationView 初始值设定项中调用 self.overrideUserInterfaceStyle。希望这对遇到此类问题的其他人有所帮助。