如何在 SwiftUI 中使用 ColorPicker 更改背景颜色?
How to change background color with ColorPicker in SwiftUI?
我是 swiftUI 的新手,我有 2 个视图。我希望在 AddTodoView 中使用 ColorPicker 我 select 一种颜色,而在 ContentView 中这种颜色显示在背景中。
内容视图
.background(AddTodoView().backgroundColor)
AddTodoView
@State var backgroundColor = Color(.systemBackground)
ColorPicker("Choosing a background color", selection: $backgroundColor)
您可以使用 @Binding
在视图之间共享数据。现在,通过调用 AddTodoView().backgroundColor
,您正在创建 AddTodoView
的 新实例 ,而您实际上想从存在于你的层次结构。
struct ContentView : View {
@State var backgroundColor : Color = Color(.systemBackground)
var body: some View {
ZStack {
backgroundColor //I'm using it in a ZStack, but you could also attach .background(backgroundColor) to any element in the hierarchy
AddTodoView(backgroundColor: $backgroundColor)
}
}
}
struct AddTodoView : View {
@Binding var backgroundColor: Color
var body: some View {
ColorPicker("Choose a color", selection: $backgroundColor)
}
}
我是 swiftUI 的新手,我有 2 个视图。我希望在 AddTodoView 中使用 ColorPicker 我 select 一种颜色,而在 ContentView 中这种颜色显示在背景中。
内容视图
.background(AddTodoView().backgroundColor)
AddTodoView
@State var backgroundColor = Color(.systemBackground)
ColorPicker("Choosing a background color", selection: $backgroundColor)
您可以使用 @Binding
在视图之间共享数据。现在,通过调用 AddTodoView().backgroundColor
,您正在创建 AddTodoView
的 新实例 ,而您实际上想从存在于你的层次结构。
struct ContentView : View {
@State var backgroundColor : Color = Color(.systemBackground)
var body: some View {
ZStack {
backgroundColor //I'm using it in a ZStack, but you could also attach .background(backgroundColor) to any element in the hierarchy
AddTodoView(backgroundColor: $backgroundColor)
}
}
}
struct AddTodoView : View {
@Binding var backgroundColor: Color
var body: some View {
ColorPicker("Choose a color", selection: $backgroundColor)
}
}