我的应用程序的很大一部分由web视图组成,以提供尚未通过本机实现提供的功能。网络团队没有计划为网站实施黑暗主题。因此,我的应用程序在iOS 13上的暗模式支持看起来会有点一半一半。

是否可以选择退出暗模式支持,这样我们的应用程序总是显示光模式,以匹配网站主题?


当前回答

根据苹果关于“在iOS上实现暗模式”(https://developer.apple.com/videos/play/wwdc2019/214/在31:13开始)的会话,可以在任何视图控制器或视图上设置overrideUserInterfaceStyle为UIUserInterfaceStyleLight或UIUserInterfaceStyleDark,这将被用于任何子视图或视图控制器的traitCollection中。

正如SeanR所提到的,你可以在应用程序的plist文件中设置uiuserinterfacstyle为Light或Dark来改变整个应用程序。

其他回答

如果你将添加UIUserInterfaceStyle键到plist文件中,苹果可能会拒绝发布构建,如这里所述:https://stackoverflow.com/a/56546554/7524146 无论如何,显式地告诉每个ViewController self是很烦人的。overrideuserinterfacstyle = .light。但是你可以在根窗口对象上使用这段代码:

if #available(iOS 13.0, *) {
    if window.responds(to: Selector(("overrideUserInterfaceStyle"))) {
        window.setValue(UIUserInterfaceStyle.light.rawValue, forKey: "overrideUserInterfaceStyle")
    }
}

请注意,你不能在应用程序(application: didFinishLaunchingWithOptions:)中这样做,因为这个选择器在早期阶段不会响应true。但你可以以后再做。如果你在你的应用中使用自定义AppPresenter或AppRouter类,而不是在AppDelegate中自动启动UI,这非常简单。

我将使用这个解决方案,因为窗口属性可能会在应用程序生命周期中发生变化。因此需要重复分配" overrideuserinterfacstyle = .light"。UIWindow.appearance()使我们能够为新创建的UIWindow对象设置默认值。

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

      if #available(iOS 13.0, *) {
          UIWindow.appearance().overrideUserInterfaceStyle = .light
      }

      return true
    }
}
 if #available(iOS 13.0, *) {
            overrideUserInterfaceStyle = .light
        } else {
            // Fallback on earlier versions
        }

在Xcode 11中,你可以在整个应用中关闭暗模式:

去Info.plist 添加波纹管 <键> UIUserInterfaceStyle关键> < / 光<字符串> < /字符串>

信息。Plist将如下所示…

如果你想退出整个应用程序,上面的答案是有效的。如果你在有UI的库上工作,并且你没有编辑.plist的奢侈,你也可以通过代码来做。

如果你正在编译iOS 13 SDK,你可以简单地使用以下代码:

迅速:

if #available(iOS 13.0, *) {
    self.overrideUserInterfaceStyle = .light
}

Obj - c:

if (@available(iOS 13.0, *)) {
    self.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
}

然而,如果你希望你的代码也能在iOS 12 SDK(目前仍然是最新的稳定SDK)上编译,你应该使用选择器。使用选择器的代码:

Swift (XCode将显示此代码的警告,但这是目前唯一的方法,因为属性不存在于SDK 12,因此不会编译):

if #available(iOS 13.0, *) {
    if self.responds(to: Selector("overrideUserInterfaceStyle")) {
        self.setValue(UIUserInterfaceStyle.light.rawValue, forKey: "overrideUserInterfaceStyle")
    }
}

Obj - c:

if (@available(iOS 13.0, *)) {
    if ([self respondsToSelector:NSSelectorFromString(@"overrideUserInterfaceStyle")]) {
        [self setValue:@(UIUserInterfaceStyleLight) forKey:@"overrideUserInterfaceStyle"];
    }
}