我有一个处理我的应用程序主题的枚举。我想要一个.system
选项,它将根据系统的主题(浅色或深色)返回不同的值。下面是我的实现方式,删除了不相关的代码:
enum Theme: String, CaseIterable, Identifiable, Codable {
case system
case dark
case light
/* more cases */
var mainColor: Color {
@Environment(\.colorScheme) var colorScheme
switch self {
case .system: return colorScheme == .dark ? .dark : .light
default: return Color(rawValue)
}
}
}
但是,当我运行它时,我收到错误Accessing Environment<ColorScheme>'s value outside of being installed on a View. This will always read the default value and will not update
。这是有道理的,因为显然枚举不是视图。话虽如此,我如何colorScheme
从枚举访问环境变量?或者有其他方法可以做到这一点吗?