10

我可以使用任何视图或 ViewController 的 TraitCollection 来获取 userInterfaceStyle,即。黑暗或光明。但是当我强制应用程序使用深色或浅色模式时,我想知道 iOS 设备的当前 userInterfaceStyle 是什么,而与应用程序无关?

我尝试了 UIScreen 的 Traitcollection,但它仍然提供应用程序的 userInterfaceStyle 而不是设备。

4

3 回答 3

28

尝试UIScreen.main,快速 5 示例:

// OS-wide theme available on iOS 13.
@available(iOS 13.0, *)
var osTheme: UIUserInterfaceStyle {
    return UIScreen.main.traitCollection.userInterfaceStyle
}
于 2019-08-29T08:52:50.480 回答
2

如果您有多个 ViewController 或 Windows 并且您希望界面样式是动态的(或者在您的情况下是锁定的),我会主张使用traitCollectionDidChange(_:)回调并查看属性userInterfaceStyle。这将反映界面样式的当前状态(即使锁定)。请记住,子视图控制器将继承其父级的设置。

通过这种方式,您可以根据当前转换的界面样式来设计代码以正确运行。下面的示例将在自定义 UIViewControllers 以及自定义 UIViews 中工作。

示例(快速 4):

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)
    if self.traitCollection.userInterfaceStyle != previousTraitCollection.userInterfaceStyle {
    // Your custom implementation here that is run right after the userInterfaceStyle has changed.
    }
}
于 2019-09-23T07:58:07.663 回答
0
         1. on first button click it will change to light mode
         2. on second button click it will change to dark mode
         3. on third button click it will adopt system theme (iphone/ipad)
        
        @IBAction func onBtn1Click(_ sender: Any) {
            if #available(iOS 13.0, *) {
                self.setTheme(theme: .light)
            } else {
                // Fallback on earlier versions
            }
        }
    
        @IBAction func onBtn2Click(_ sender: Any) {
        if #available(iOS 13.0, *) {
            self.setTheme(theme: .dark)
        } else {
            // Fallback on earlier versions
        }
    }

@IBAction func onBtn3Click(_ sender: Any) {
    if #available(iOS 13.0, *) {
        self.setTheme(theme: .unspecified)
    } else {
        // Fallback on earlier versions
    }
}

@available(iOS 13.0, *)
func setTheme(theme : UIUserInterfaceStyle) {
    let keyWindow = UIApplication.shared.connectedScenes
        .filter({$0.activationState == .foregroundActive})
        .compactMap({$0 as? UIWindowScene})
        .first?.windows
        .filter({$0.isKeyWindow}).first
    
    if theme == .light {
        keyWindow?.overrideUserInterfaceStyle = .light
    } else if theme == .dark {
        keyWindow?.overrideUserInterfaceStyle = .dark
    } else {
        if UIScreen.main.traitCollection.userInterfaceStyle == .dark {
            keyWindow?.overrideUserInterfaceStyle = .dark
        } else {
            keyWindow?.overrideUserInterfaceStyle = .light
        }
    }
}
于 2022-01-27T04:27:43.550 回答