最近因?yàn)樾枰捌鹨荒曛暗墓卷?xiàng)目,iOS 13 系統(tǒng)下需要進(jìn)行適配的太多了,做個(gè)總結(jié)吧。
這里小伙伴們需要了解
UITraitCollection
在 iOS 13 中, UITraitCollection 來(lái)判斷當(dāng)前系統(tǒng)的模式。UIView
、UIViewController
、UIScreen
、UIWindow
都遵從了UITraitEnvironment
這個(gè)協(xié)議,這幾個(gè)類都擁有一個(gè)叫做 traitCollection
的屬性,所以我們可以根據(jù)這個(gè)屬性判斷當(dāng)前 App 的顏色模式:
BOOL isDark = (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark);
還可以通過 UITraitCollection.current
這個(gè)屬性來(lái)獲取當(dāng)前 App 的顏色模式。
官方說(shuō)明只有在下面這些方法中,才可以使用這個(gè)屬性:
UIView
draw()
layoutSubview()
traitCollectionDidChange()
tintColorDidChange()
UIViewController
viewWillLayoutSubviews()
viewDidLayoutSubviews()
traitCollectionDidChange()
UIPresentationController
containerViewWillLayoutSubviews()
containerViewDidLayoutSubviews()
traitCollectionDidChange()
1.代碼顏色配置:
{
if (@available(iOS 13.0, *)) {
return [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull tc) {
if (tc.userInterfaceStyle == UIUserInterfaceStyleLight){//普通模式
return lightColor;
}else if (tc.userInterfaceStyle == UIUserInterfaceStyleDark){//暗夜模式
return darkColor;
}
return lightColor;
}];
} else {
return lightColor;
}
}
2:圖片適配
1.創(chuàng)建一個(gè)Assets文件(或在現(xiàn)有的Assets文件中)
詳情請(qǐng)看:iOS中創(chuàng)建多個(gè)Assets.xcassets文件2.新建一個(gè)圖片資源文件(或者顏色資源文件、或者其他資源文件)
-
3.選中該資源文件, 打開 Xcode ->View ->Inspectors ->Show Attributes Inspectors (或者Option+Command+4)視圖,將Apperances 選項(xiàng) 改為
Any,Dark
1.png -
4.執(zhí)行完第三步,資源文件將會(huì)有多個(gè)容器框,分別為
Any Apperance
和Dark Apperance
.Any Apperance
應(yīng)用于默認(rèn)情況(Unspecified
)與高亮情況(Light
),Dark Apperance
應(yīng)用于暗黑模式(Dark
)
2.png 5.代碼默認(rèn)執(zhí)行時(shí),就可以正常通過名字使用了,系統(tǒng)會(huì)根據(jù)當(dāng)前模式自動(dòng)獲取對(duì)應(yīng)的資源文件
注意啦??,同一項(xiàng)目工程內(nèi)如果新建了多個(gè)Assets文件,在我們打包后,系統(tǒng)會(huì)自動(dòng)會(huì)生成一個(gè)新的Assets.car 文件,所以必須要保證Assets內(nèi)資源文件的名字命名唯一性.
2.全局關(guān)閉暗黑模式
系統(tǒng)配置:
在Info.plist 文件中,添加UIUserInterfaceStyle
key 名字為 User Interface Style
值為String
,
將UIUserInterfaceStyle
key 的值設(shè)置為 Light
代碼配置;
代碼關(guān)閉黑暗模式 強(qiáng)制關(guān)閉暗黑模式
if(@available(iOS 13.0,*)){
self.window.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
}
#endif
3.單一配置暗夜模式
在 iOS 13中,UIView
、UIViewController
、UIWindow
有了一個(gè) overrideUserInterfaceStyle
的新屬性,可以覆蓋系統(tǒng)的模式。
單個(gè)頁(yè)面或視圖開啟或者關(guān)閉暗黑模式,設(shè)置 overrideUserInterfaceStyle
為對(duì)應(yīng)的模式,強(qiáng)制限制該視圖與其子視圖以設(shè)置的模式進(jìn)行展示,不跟隨系統(tǒng)模式改變進(jìn)行改變。
self.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
這樣設(shè)置會(huì)影響當(dāng)前view
viewController
window
以及它下面的任何子內(nèi)容。
單一視圖監(jiān)聽系統(tǒng)的模式, overrideUserInterfaceStyle
屬性設(shè)置為.unspecified
就可以了。
參考資料:
How To Adopt Dark Mode In Your iOS App
Backwards compatibility for iOS 13 system colors