[英]How to switch programmatically to dark mode swift
如何在我的 iOS 應用程序中切換以編程方式更改為暗模式或亮模式? 我正在使用斯威夫特。
如何在iOS應用中進行切換,以編程方式更改為暗或亮模式? 我正在使用Swift。
您可以使用其中一種觀察方式,例如Defaults
lib,然后添加
window.overrideUserInterfaceStyle = .dark
到
func場景(_場景:UIScene,willConnectTo會話:UISceneSession,選項connectionOptions:UIScene.ConnectionOptions){}
方法
我想詳細說明@Frank Schlegel 提供的答案。
要從應用程序中的另一個視圖控制器更改主題(我認為這是您最初要求的),您可以為UserDefaults
值添加一個觀察者,該值將觸發更改。
我會添加一個枚舉以更好地代表主題狀態
enum Theme: String {
case light, dark, system
// Utility var to pass directly to window.overrideUserInterfaceStyle
var uiInterfaceStyle: UIUserInterfaceStyle {
switch self {
case .light:
return .light
case .dark:
return .dark
case .system:
return .unspecified
}
}
}
在您的window
初始化下的SceneDelegate
,您必須添加每次UserDefaults
更改值時觸發的此方法。
UserDefaults.standard.addObserver(self, forKeyPath: "theme", options: [.new], context: nil)
此外,您想在取消SceneDelegate
時刪除該觀察者,添加
deinit {
UserDefaults.standard.removeObserver(self, forKeyPath: "theme", context: nil)
}
這將在UserDefaults
中放置該theme
值的觀察者。
要處理更改,您需要將此方法添加到SceneDelegate
類。
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard
let change = change,
object != nil,
keyPath == Defaults.theme.rawValue,
let themeValue = change[.newKey] as? String,
let theme = Theme(rawValue: themeValue)?.uiInterfaceStyle
else { return }
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveLinear, animations: { [weak self] in
self?.window?.overrideUserInterfaceStyle = theme
}, completion: .none)
}
這將在UserDefaults
中的每次theme
值更改時執行,並將動畫從一個主題到另一個主題的過渡。
現在,要從應用程序中的其他視圖控制器更改主題,您只需更改UserDefaults
的值。
UserDefaults.standard.setValue(Theme.light.rawValue, forKey: "theme")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.