In this view controller, there is a button that changes between light and dark mode using the following code:
@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
}
...
}
There is a mapbox map view inside of the view controller that has annotations that I add through layers. And when the function above executes, it clears the map and annotations and re-adds them.
The problem is in this annotation view, when I try to update the background color based on the userInterfaceStyle, the style is always stuck to the device system appearance (whichever one the user loads in with) and does not update. The print statement you see there only prints out the default value over and over.
class CustomAnnotationView: MGLAnnotationView {
init() { ... }
override func draw(_ rect: CGRect) {
...
print("-----> \(UITraitCollection.current.userInterfaceStyle.rawValue)")
let fillColor: UIColor = UITraitCollection.current.userInterfaceStyle == .dark ? .orange : .darkgrey
...
}
}
How do I get this view to retrieve the overrideUserInterfaceStyle style? traitCollectionDidChange function in here never executes when I add it either (presumably because the annotation is created from scratch every time which makes sense).
The reason I don't just set the color to a system one that changes between colors depending on the userInterfaceStyle, is because I eventually cast this annotationView to an image that I add in as a layer to the map. Because it's an image, it would not update the color. So I have to completely wipe the map and add the annotations back to get the correct appearance.
The issue stemmed from the UIView not having a parent when I initialized it so it had nowhere to read the traitCollection from and fell back to using the system settings. The fix was to pass in the userInterfaceStyle from the viewController and calling self.overrideUserInterfaceStyle
inside of the CustomAnnotationView initializer. Hopefully this helps anyone else who runs into this kind of issue.