不管是UIView,还是UIViewController或者子类
在切换 ”设置“ 中的 “显示与亮度” 中 模式时,都会调用一个方法,这个方法是系统API
swift:
//MARK:暗黑模式监听 override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if #available(iOS 13.0, *) { if self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) { if UITraitCollection.current.userInterfaceStyle==UIUserInterfaceStyle.dark { //暗黑模式 }else{ //明亮模式 } } } else { // Fallback on earlier versions } }
oc:
//MARK:暗黑模式监听 - (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection{ [super traitCollectionDidChange:previousTraitCollection]; if (@available(iOS 13.0, *)) { if ([[UITraitCollection currentTraitCollection] userInterfaceStyle]==UIUserInterfaceStyleDark) { } else{ } } else { // Fallback on earlier versions } }
往往在初始化View时也要区分一下,是明亮模式还是暗黑模式。即使一上来会调用以上的方法,毕竟在VC中创建View不会写到以上代理方法。
swift:
if #available(iOS 13.0, *) { if UITraitCollection.current.userInterfaceStyle==UIUserInterfaceStyle.dark { //暗黑模式 }else{ //明亮模式 } } else { // Fallback on earlier versions }
oc:
if (@available(iOS 13.0, *)) { if ([[UITraitCollection currentTraitCollection] userInterfaceStyle]==UIUserInterfaceStyleDark) { } else{ } } else { // Fallback on earlier versions }
对颜色的适配就是这样的。
而图片适配请参考:https://www.jianshu.com/p/476cac3851c8?utm_campaign=maleskine
///////////////////////////////////////////////////////////////////////////
额外的,对WKWebView适配:在didFinished代理方法里面写
//适配暗黑模式 var backgroundColor : String = "" var labelColor : String = "" if #available(iOS 13.0, *) { if UITraitCollection.current.userInterfaceStyle==UIUserInterfaceStyle.dark { //暗黑模式 backgroundColor = ""#000000""; labelColor = "'#828282'"; }else{ //明亮模式 backgroundColor = ""#FFFFFF""; labelColor = "'#666666'"; } } else { // Fallback on earlier versions } webView.evaluateJavaScript(String(format: "document.body.style.backgroundColor=%@", backgroundColor)) { (obj, error) in } webView.evaluateJavaScript(String(format: "document.getElementsByTagName('body')[0].style.webkitTextFillColor=%@", labelColor)) { (obj, error) in }