Давайте рассмотрим пример. У меня есть собственное значение среды:
Код: Выделить всё
enum Theme {
case black
case white
func color() -> Color {
// ... Get color functional
}
}
struct ThemeKey: EnvironmentKey {
static let defaultValue: Theme = .black
}
extension EnvironmentValues {
var theme: Theme {
get { self[ThemeKey.self] }
set { self[ThemeKey.self] = newValue }
}
}
Код: Выделить всё
struct AppView: View {
var body: some View {
ContentView()
.environment(\.theme, .white)
}
}
}
struct ContentView: View {
@Environment (\.theme) private var theme
var body: some View {
Rectangle()
.fill(theme.color())
}
}
Код: Выделить всё
extension View {
var theme: Theme {
return Environment(\.theme).wrappedValue
}
}
struct ContentView: View {
var body: some View {
Rectangle()
.fill(theme.color())
}
}
Поэтому мой вопрос: нужно ли мне добавлять свойство @Environment в мое представление для доступа к теме< /code> или можно сделать это другим способом, например, не объявляя свойство @Environment?
Подробнее здесь: https://stackoverflow.com/questions/782 ... swiftuis-v
Мобильная версия