I was creating the method in UIView extension and I needed to change UIColor according to UIUserInterfaceStyle i.e. separate UIColor for both Dark & Light mode Interface.
Usually, in
UIViewController
classtraitCollectionDidChange
method
is triggered whenever UIUserInterfaceStyle is changed and we can
determine the current user interface style by
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.changeUIWithUserInterface(style: self.traitCollection.userInterfaceStyle)
}
}
But the Extension of UIView does not have traitCollectionDidChange method that can be triggered
so how can I change the UIColor according to UIUserInterfaceStyle in UIView extension?
I figured it out and thought to post it for fellow devs.
Hope It Helps 🙂
2
Answers
Below method works like a charm for me!
It is triggered whenever
traitCollection
changes..It can work on any extension of various UI components
Reference: Thanks to answer of @ElanoVasconcelos
You can set UIColor as simple variable, that automatically changes when
traitCollection
changes:Usage: