[英]SwiftUI: Get the Dynamic Background Color (Dark Mode or Light Mode)
有沒有辦法系統地訪問 SwiftUI 視圖的標准動態背景顏色,而不管用戶是處於明模式還是暗模式?
例如,我知道以下內容可用於獲取主要(例如文本)顏色:
let textColor = Color.primary
...但我沒有看到任何類似的獲得背景顏色的東西。
let backgroundColor = Color.??? // Not available
我正在尋找適用於 iOS 和 macOS 的東西。
因此,目前似乎沒有任何此類屬性內置到 SwiftUI 的與操作系統無關的Color
類中; 但是, UIColor
和NSColor
確實為它提供了訪問器(分別在 iOS 和 macOS 上),您可以使用這些較舊的顏色對象來初始化 SwiftUI Color
對象。
因此,您可以使用Color
的簡單擴展來實現您的需求,如下所示,它使用條件編譯在任一操作系統上正常工作。
無需使用此方法檢查colorScheme
或userInterfaceStyle
:當用戶在colorScheme
模式之間切換時,操作系統將自動切換。
我還包括了 'secondary' 和 'tertiary' 顏色,它們在 macOS 上有點主觀,但如果需要,您可以隨時將它們更改為其他一些NSColor
屬性。
斯威夫特 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
一樣從代碼中的其他地方訪問這些。 例如:
let backgroundColor = Color.background
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.