如何检查iOS / iPadOS中是否启用了暗模式?

Tam*_*gel 25 ios ios13 ipados ios-darkmode

从iOS / iPadOS 13开始,提供了深色用户界面样式,类似于macOS Mojave中引入的深色模式。如何检查用户是否已启用系统范围的暗模式?

Tam*_*gel 20

您应该检查的userInterfaceStyle变量UITraitCollection,与tvOS和macOS相同。

switch traitCollection.userInterfaceStyle {
case .light: //light mode
case .dark: //dark mode
case .unspecified: //the user interface style is not specified
}
Run Code Online (Sandbox Code Playgroud)

您应该使用/ 的traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)功能来检测界面环境的变化(包括用户界面样式的变化)。UIViewUIViewController

Apple开发人员文档中

当iOS界面环境更改时,系统会调用此方法。根据您的应用程序的需求,在视图控制器和视图中实现此方法以响应此类更改。例如,当iPhone从纵向旋转为横向时,您可以调整视图控制器的子视图的布局。此方法的默认实现为空。

系统默认的UI元素(例如UITabBarUISearchBar)会自动适应新的用户界面样式。

  • 除了`traitCollectionDidChange(_:)`,你还可以检查`UIView`的`layoutSubviews()`、`draw(_:)`、`updateConstraints()`或`tintColorDidChange()`中的变化,或在`UIViewController` 的`updateViewConstraints()`、`viewWillLayoutSubviews()` 或`viewDidLayoutSubviews()` 中。每次用户界面样式更改时,都会调用所有这些方法。 (3认同)
  • 这将为您提供当前视图的用户界面样式。如果您已针对特定视图覆盖了它,它将不会告诉您系统的样式。 (2认同)

小智 13

1/ 对于 UIView/UIViewController:

self.traitCollection.userInterfaceStyle == .dark
Run Code Online (Sandbox Code Playgroud)

2/ 对于静态或其他:

UITraitCollection.current.userInterfaceStyle == .dark
Run Code Online (Sandbox Code Playgroud)

但:

//Never use this! You will get wrong value in app extensions (ex. ToDay widget)
UIScreen.main.traitCollection.userInterfaceStyle == .dark //WRONG!
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这可能会对某人有所帮助:如果您在“info.plist”中将“UIUserInterfaceStyle”设置为“light”,则此方法将始终返回“light” (3认同)
  • 实际上,最后一个(UIScreen ...)是在覆盖我的应用程序中的 userInterfaceStyle 之后在设备设置中获取用户的暗模式设置的唯一方法。通过这种方式,我能够实现一个“遵循 iOS 深色模式”按钮,该按钮会立即更新应用程序的颜色主题,即使我除此之外还有自定义主题和选择。不幸的是,如果不覆盖 userInterfaceStyle,就不可能单独可靠地管理状态栏文本颜色。 (2认同)

Ped*_*llo 13

对于斯威夫特:

if #available(iOS 12.0, *) {
  switch UIScreen.main.traitCollection.userInterfaceStyle {
    case .dark: // put your dark mode code here
    case .light: 
    case .unspecified: 
  }
}
Run Code Online (Sandbox Code Playgroud)

对于目标 C:

if (@available(iOS 12.0, *)) {
        switch (UIScreen.mainScreen.traitCollection.userInterfaceStyle) {
            case UIUserInterfaceStyleDark:
                // put your dark mode code here
                break;
            case UIUserInterfaceStyleLight:
            case UIUserInterfaceStyleUnspecified:
                break;
            default:
                break;
        }
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请观看此 WWDC2019视频

  • 我最终在我的 iOS 项目中将它用于 Xamarin.Forms。到目前为止最好的答案。(消息灵通的可靠答案比 MS for Xamarin 的官方 doku 的一些博主的第 100 个副本更好。)@Pedro Trujillo 你拯救了我的一天。谢谢! (3认同)

Ely*_*Ely 12

如daveextreme所提到的,使用属性时,检查当前视图用户界面样式并不总是返回系统样式overrideUserInterfaceStyle。在这种情况下,最好使用以下代码:

switch UIScreen.main.traitCollection.userInterfaceStyle {
case .light: //light mode
case .dark: //dark mode
case .unspecified: //the user interface style is not specified
}
Run Code Online (Sandbox Code Playgroud)


Moj*_*ini 11

用户界面

使用变量的\.colorSchemeEnvironment

struct ContentView: View {
    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        Text(colorScheme == .dark ? "In dark mode" : "In light mode")
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,它会根据环境配色方案的变化自动更新。


用户界面工具包

要检查当前,所有符合UITraitEnvironment协议的对象,包括所有UIView子类和所有UIViewConttroller子类都可以访问当前样式:

myUIView.traitCollection.userInterfaceStyle == .dark
myUIViewController.traitCollection.userInterfaceStyle == .dark
Run Code Online (Sandbox Code Playgroud)

要检测样式的实时变化,这里是完整的详细答案


huy*_*ync 8

对于iOS 13,您可以使用此属性来检查当前样式是否为暗模式:

if #available(iOS 13.0, *) {
    if UITraitCollection.current.userInterfaceStyle == .dark {
        print("Dark mode")
    }
    else {
        print("Light mode")
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您想签入 AppDelegate,这非常有用,因为它没有像“UIViewController”那样的“traitCollection”变量 (4认同)
  • 这不会对禁用的黑暗模式做出反应。如果您使用“window?.overrideUserInterfaceStyle = .light”,则“UITraitCollection.current.userInterfaceStyle”可以返回“.dark”。 (2认同)

bir*_*man 8

目标 C

要通过控制中心检测何时启用或禁用暗模式,请使用“appDidBecomeActive”通知,该通知将在您返回应用程序时触发。

//----------------------------------------------------------------------------
//                          viewWillAppear
//----------------------------------------------------------------------------
- (void)viewWillAppear {
    [super viewWillAppear];

    [[NSNotificationCenter defaultCenter]addObserver:self
                                   selector:@selector(appDidBecomeActive:)
                                   name:UIApplicationDidBecomeActiveNotification
                                   object:nil];

}
Run Code Online (Sandbox Code Playgroud)

完成后不要忘记将其删除:

//------------------------------------------------------------------------------------
//                    viewWillDisappear
//------------------------------------------------------------------------------------
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self        
                                 name:UIApplicationDidBecomeActiveNotification 
                                 object:nil];

}
Run Code Online (Sandbox Code Playgroud)

在暗模式更改时执行您需要的操作:

//----------------------------------------------------------------------------
//                          appDidBecomeActive
//----------------------------------------------------------------------------
-(void)appDidBecomeActive:(NSNotification*)note {
    if (@available(iOS 13.0, *)) {
        if( self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark ){
            //dark mode
        }
        else {
            //not dark mode
        }
    }
    else {
        //fall back for older versions
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

为 write 方法创建一个类函数 1 次并在任何你想要的地方使用

func isDarkMode() -> Bool{
    if #available(iOS 12.0, *) {
        if UIScreen.main.traitCollection.userInterfaceStyle == .dark {
            return true
        } else {
            return false
        }
    } else {
       return false
    }
}  
Run Code Online (Sandbox Code Playgroud)


Luc*_*hwe 7

下面的辅助方法适用于任何 iOS 版本:

var isDarkMode: Bool {
    guard #available(iOS 12.0, *) else {
        return false
    }

    return UIScreen.main.traitCollection.userInterfaceStyle == .dark
}
Run Code Online (Sandbox Code Playgroud)

用法:

view.backgroundColor = isDarkMode ? .black : .white
Run Code Online (Sandbox Code Playgroud)

  • 欢迎来到堆栈溢出。没有任何解释的代码转储很少有帮助。Stack Overflow 是关于学习的,而不是提供用于盲目复制和粘贴的片段。请[编辑]你的问题并解释它如何比OP提供的更好。 (2认同)

jbi*_*361 5

在Objective-C中,您想要执行以下操作:

if( self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark ){

        //is dark
}else{

    //is light

}
Run Code Online (Sandbox Code Playgroud)