代碼適配
- 獲取當前的模式
UITraitCollection.current.userInterfaceStyle
- 判斷是否是暗黑模式
if UITraitCollection.current.userInterfaceStyle == .dark {
//暗黑模式
} else {
//其他模式
}
- 監(jiān)聽顯示模式的改變方法
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 13.0, *) {
//是否改變
if self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
//不同
if self.currentStyle == false {
self.view.backgroundColor = .black
self.lbl?.text = "Dark"
self.lbl?.textColor = .white
} else {
self.view.backgroundColor = .white
self.lbl?.text = "Light"
self.lbl?.textColor = .black
}
self.currentStyle = !self.currentStyle
}
} else {
// Fallback on earlier versions
}
}
圖片適配
-
在Assets.xcassets中,點擊圖片-右邊第四個(command+option+4快捷鍵),里面有個Appearance,選擇Any,Dark,最后將暗黑模式所需要的圖片拖進去即可。
image.png
