SwiftUI:获取动态背景色(暗模式或亮模式) [英] SwiftUI: Get the Dynamic Background Color (Dark Mode or Light Mode)

查看:100
本文介绍了SwiftUI:获取动态背景色(暗模式或亮模式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以系统地访问SwiftUI视图的标准动态背景色,而不管用户是处于亮模式还是暗模式?

Is there a way to systematically access the standard, dynamic background color for SwiftUI views, regardless of whether the user be in Light or Dark Mode?

例如,我知道以下内容可用于获取主要(例如文本)颜色:

For example, I know the following can be used to get the primary (e.g. text) color:

let textColor = Color.primary

...但是我看不到任何类似的背景色.

...but I don't see anything similar for getting the background color.

let backgroundColor = Color.??? // Not available

我正在寻找在iOS和macOS上都可以使用的东西.

I'm looking for something that works on both iOS and macOS.

推荐答案

因此,目前在SwiftUI的独立于操作系统的 Color 类中似乎没有内置任何此类属性;但是, UIColor NSColor do 为此提供了访问器(分别在iOS和macOS上),您可以使用这些较旧的颜色对象来初始化SwiftUI Color 对象.

So there doesn't currently appear to be any such property built into SwiftUI's OS-independent Color class; however, UIColor and NSColor do provide accessors for it (on iOS and macOS respectively), and you can use these older color objects to initialize a SwiftUI Color object.

因此,可以使用对 Color 的简单扩展来实现所需的功能,如下所示,该扩展使用条件编译在任一OS上都能正常工作.

As a result, what you need can be achieved using a simple extension to Color, such as the below, which uses conditional compilation to work correctly on either OS.

无需使用以下方法检查 colorScheme userInterfaceStyle :当用户在Light& amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; #####之间之间切换时,操作系统会自动切换.暗模式.

No need to check colorScheme or userInterfaceStyle with this approach: The OS will switch automatically when the user moves between Light & Dark mode.

我还添加了中学"和"第三级"颜色在macOS上有点主观,但是如果需要,您可以随时将其更改为其他一些 NSColor 属性.

I've also included 'secondary' & 'tertiary' colors, which are a little subjective on macOS, but you can always change them to some of the other NSColor properties if you want.

Swift v5.2:

import SwiftUI

public extension Color {

    #if os(macOS)
    static let background = Color(NSColor.windowBackgroundColor)
    static let secondaryBackground = Color(NSColor.underPageBackgroundColor)
    static let tertiaryBackground = Color(NSColor.controlBackgroundColor)
    #else
    static let background = Color(UIColor.systemBackground)
    static let secondaryBackground = Color(UIColor.secondarySystemBackground)
    static let tertiaryBackground = Color(UIColor.tertiarySystemBackground)
    #endif
}

然后,您可以像其他任何SwiftUI Color 一样,从代码中的其他位置访问这些内容.例如:

You then simply access these from elsewhere in your code like any other SwiftUI Color. For example:

let backgroundColor = Color.background

这篇关于SwiftUI:获取动态背景色(暗模式或亮模式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆