如何在 SwiftUI 中使用 ColorPicker 更改背景颜色?

我是 swiftUI 的新手,我有 2 个视图。我希望使用 ColorPicker 在 AddTodoView 中选择一种颜色,并在 ContentView 中将该颜色显示在背景中。

内容视图 .background(AddTodoView().backgroundColor)

添加TodoView @State var backgroundColor = Color(.systemBackground) ColorPicker("Choosing a background color",selection: $backgroundColor)

tx5897932 回答:如何在 SwiftUI 中使用 ColorPicker 更改背景颜色?

您可以使用 @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)
    }
}
本文链接:https://www.f2er.com/1188.html

大家都在问