【发布时间】:2016-09-18 21:29:12
【问题描述】:
如何检查用户是否在其 Apple TV 上启用了深色外观?
【问题讨论】:
如何检查用户是否在其 Apple TV 上启用了深色外观?
【问题讨论】:
使用UIUserInterfaceStyle,首先在 tvOS 10 中可用,我们可以检查用户设置的外观。
例如:
func checkInterfaceStyle() {
guard(traitCollection.responds(to: #selector(getter: UITraitCollection.userInterfaceStyle)))
else { return }
let style = traitCollection.userInterfaceStyle
switch style {
case .light:
print("light")
case .dark:
print("dark")
case .unspecified:
print("unspecified")
}
}
此外,如果您是从 Xcode 7/tvOS 9.0 项目更新,则需要在您的 info.plist 中包含 UIUserInterfaceStyle。使用 Xcode 8 创建的新项目已经包含此密钥。
<key>UIUserInterfaceStyle</key>
<string>Automatic</string>
【讨论】:
viewDidLoad。确保您的 info.plist 中也包含密钥。
if traitCollection.userInterfaceStyle == .dark {
}
【讨论】:
我在 Swift 5 中编写了这个扩展:
extension UIViewController {
var isDarkModeEnabled : Bool {
get {
return traitCollection.userInterfaceStyle == .dark
}
}
}
然后你可以在你的 UIViewControllers 中调用它:
if self.isDarkModeEnabled {
//Do something dark
} else {
//Do something light
}
【讨论】: