[英]Turn on system dark mode from app - Swift
我已經使用Notifications
在我的應用程序上創建了自己的暗模式系統,並且我有一個可以在暗模式打開和關閉之間切換的開關。
我的第一個問題:如何打開系統暗模式,如果通過撥動開關更新到 iOS 13,整個手機也會進入暗模式。
我的第二個問題:如何檢查是否啟用了系統暗模式,以便在啟用 iOS 系統暗模式時,我可以在啟用暗模式的地方進行設置?
您應該檢查UITraitCollection
的userInterfaceStyle
變量,與 tvOS 和 macOS 相同。
switch traitCollection.userInterfaceStyle {
case .light: //light mode
case .dark: //dark mode
case .unspecified: //the user interface style is not specified
}
您應該使用UIView
/ UIViewController
的traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
函數來檢測界面環境的變化(包括用戶界面風格的變化)。
來自Apple 開發者文檔:
當iOS界面環境發生變化時,系統會調用該方法。 根據您的應用程序的需要,在視圖控制器和視圖中實現此方法以響應此類更改。 例如,當 iPhone 從縱向旋轉到橫向時,您可能會調整視圖控制器子視圖的布局。 此方法的默認實現為空。
系統默認 UI 元素(例如UITabBar
或UISearchBar
)會自動適應新的用戶界面樣式。
if #available(iOS 13.0, *) {
overrideUserInterfaceStyle = .light // or .dark
} else {
// Fallback on earlier versions
}
使用此方法您將獲得亮模式和暗模式,將此代碼放入開關中,您的視圖將根據暗和亮的外觀而變化。
第一個問題:在 AppDelegate 中
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let darkModeStatus = UserDefaults.standard.bool(forKey: "darkModeStatus") if darkModeStatus == true { window?.overrideUserInterfaceStyle = .dark } else { window?.overrideUserInterfaceStyle = .light } return true }
第二個問題:在VC中使用Toggle Switch
@IBAction func darkModeSwitchClicked(_ sender: Any) { if darkModeToggleSwitch.isOn { UserDefaults.standard.set(true, forKey: "darkModeStatus") } else { UserDefaults.standard.set(false, forKey: "darkModeStatus") } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.