PlusNightMode

PlusNightMode 使您的应用程序可以轻松添加用户可配置的浅色模式、深色模式、自动(操作系统设置)和夜间模式。它专为 SwiftUI 设计。

章节

什么是夜间模式?

众所周知,夜间暴露在光线下会减少我们身体褪黑素的产生。在 WWDC 23 上,Apple 推出了一种创新的方法来解决这个问题,“夜间模式”。这是一种“红色比例”的 UI 视觉外观,这意味着屏幕上的每个像素要么是黑色,要么是红色阴影。这对于 2 个主要原因非常有价值。首先,显示的整体光线更少。其次,过滤掉蓝光(对褪黑素产生最负面影响)。但是,目前,Apple 的夜间模式仅适用于 iOS 17 的 StandBy 和一个表盘。现在,您只需几行代码即可将夜间模式添加到您的应用程序。

换句话说,夜间模式可以保护您的用户免受危害健康、剥夺睡眠的光线。

用法

只需将 .observingNightMode() 添加到您的 View 层次结构的顶部,如下所示

struct NightModeView: View {
    @Environment(\.colorSchemeMode) var colorSchemeMode // 👈🏼

    var body: some View {
      NavigationStack {
        List {
          Image(.blindingWhite)
            .resizable()
            .frame(maxWidth: .infinity)
            .aspectRatio(1.0, contentMode: .fill)
          Text("This is a text view")
          Text("Blue").foregroundStyle(.blue)
          Text("Green").foregroundStyle(.green)
          Text("Yellow").foregroundStyle(.yellow)
          NavigationLink("Go to second page", value: "second page")
        }
        .navigationTitle("Hello World!")
        .navigationDestination(for: String.self) { string in
          Text(string)
        }
      }
      .colorSchemeMode($colorSchemeMode) // 👈🏼
    }
}

这将把该 View 及其所有子 View 转换为夜间模式。

请注意,呈现的 View 不被 SwiftUI 视为子 View。 因此,每当您呈现一个 View(例如在 .sheet 中)时,您也必须将 .observingNightMode() 应用于该呈现的 View。

struct ExampleView: View {
  @Environment(\.colorSchemeMode) var colorSchemeMode

  var body: some View {
    Button {
      isPresenting.toggle()
    } label: {
      Text("Present Sheet View")
    }
    .colorSchemeMode($colorSchemeMode)
    .sheet(isPresented: $isPresenting) {
      Text("Presented View")
        .colorSchemeMode($colorSchemeMode)
        // 👆🏼 SwiftUI will not add Night Mode to 
        // presented views unless you explicitly add it
    }
  }
}

🚀 但是,有一种更好的方法来添加夜间模式,它甚至可以响应设备当前的深色模式设置。它被称为 ColorSchemeMode

ColorSchemeMode

PlusNightMode 还附带 ColorSchemeMode,这是一个简单的包装结构,它为 SwiftUI 的 ColorScheme 添加了一些功能,包括夜间模式。 要使用,只需在您的模型中的某个位置创建并存储一个 ColorSchemeMode。 然后在您的 View 层次结构的顶部设置 .colorSchemeMode()

struct ExampleView: View {
  @State var colorSchemeMode: ColorSchemeMode = .night


  var body: some View {
    Text("Hello world")
      .colorSchemeMode($colorSchemeMode)
  }
}

ColorSchemeMode 可以具有以下值

对于您希望在整个应用程序中保持同步的用户可配置的 ColorSchemeMode,请尝试使用 EnvironmentValue

@Environment(\.colorSchemeMode) var colorSchemeMode
// ... 
MyView()
  .colorSchemeMode($colorSchemeMode)

对于即使在应用程序关闭后也可以持久化的 ColorSchemeMode,请尝试使用 @AppStorage

@AppStorage("colorSchemeMode") var colorSchemeMode

MyView()
  .colorSchemeMode($colorSchemeMode)

已知限制

我们只能将夜间模式应用于 SwiftUI View 层次结构中的 View。 这不包括系统 View,例如屏幕顶部的状态栏。

某些 SwiftUI View 无法设置样式或覆盖。 例如,当用户点击 SwiftUI Menu 时。 请注意,呈现的菜单处于深色模式,而不是夜间模式。 如果您找到解决方法,请打开 Issue 或 PR。

设计考虑

请务必在所有用例中测试您的设计。 一些需要注意的事项

协作

请随时打开 PR。

致谢