SwiftUI中Rectangle上下文菜单的颜色选择器为何禁用?
Rectangle上下文菜单中ColorPicker禁用的原因及解决方法
最常见的原因是你给ColorPicker绑定的是不可变的常量(比如用let声明的颜色变量),而ColorPicker需要绑定一个可以被修改的状态属性,否则系统会自动禁用它。
举个错误的例子,这种写法里ColorPicker就是禁用的:
struct ContentView: View { // 用let声明的常量,无法修改 let rectangleColor = Color.red var body: some View { Rectangle() .fill(rectangleColor) .frame(width: 200, height: 200) .contextMenu { // 绑定不可变的常量,选择器禁用 ColorPicker("选择颜色", selection: $rectangleColor) } } }
只要把颜色变量改成用@State(或者@Binding、@ObservedObject里的属性等状态包装器)修饰的可变属性,选择器就能正常使用了:
struct ContentView: View { // 用@State包装,让变量成为可被修改的状态 @State private var rectangleColor = Color.red var body: some View { Rectangle() .fill(rectangleColor) .frame(width: 200, height: 200) .contextMenu { // 绑定可变的状态变量,选择器正常工作 ColorPicker("选择颜色", selection: $rectangleColor) } } }
如果你的Rectangle是在子视图里,记得用@Binding把父视图的状态传递过来,而不是直接传值:
// 子视图 struct ColorRectView: View { @Binding var rectColor: Color var body: some View { Rectangle() .fill(rectColor) .frame(width: 200, height: 200) .contextMenu { ColorPicker("选择颜色", selection: $rectColor) } } } // 父视图 struct ContentView: View { @State private var mainColor = Color.blue var body: some View { ColorRectView(rectColor: $mainColor) } }
核心逻辑就是:ColorPicker需要能修改绑定的变量,所以必须绑定到可变的状态属性上,不能绑定不可变的常量。
内容的提问来源于stack exchange,提问作者Vargunini
相关产品推荐
相关产品推荐

