Reputation: 53
I've found a couple questions on here related to the issue I'm having but since I'm fairly new to iOS development I'm not sure how/where people are implementing their solutions. Since I am also new to StackOverflow I cannot comment on their posts so any help would be greatly appreciated.
Detecting iOS Dark Mode Change
How to detect Light\Dark mode change in iOS 13?
I have a collectionView that when I change to and from Dark Mode, the cell borderColor is changing to what looks like black instead of the color it should be based on the systemGray color that I have assigned to it.
In the answers I linked above people suggested using layoutSubviews() and/or traitCollectionDidChange() but I'm not exactly sure where to implement those functions. I can't seem to find the functions in the definitions of UIViewController or UICollectionView.
When I reload the views using reloadData(), the colors change to what they should be but I would like to know when/where the functions layoutSubviews() and/or traitCollectionDidChange() are being called.
Upvotes: 4
Views: 5509
Reputation: 197
If you'd like to understand how to implement dark mode in iOS 13 I would suggest you watch this wwdc video. However, if you just want a quick understanding of when the methods are called, here is a summary:
layoutSubviews()
: The layoutSubviews method is for UIView
subclasses. You can override this in your own UIView
subclasses like so:
class CustomCollectionView: UICollectionView {
override func layoutSubviews() {
super.layoutSubviews()
// your implementation here
}
}
traitCollectionDidChange()
: The traitCollectionDidChange method can be overrided for UIViewController
subclasses. You can override this in your own UIViewController
subclasses like so:
class CustomViewController: UIViewController {
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// your implementation here.
}
}
If you want to specifically know when the theme has changed then your implementation of traitCollectionDidChange
would look something like:
public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 13, *), traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
// handle theme change here.
}
}
Upvotes: 10