可选,在swiftUI中绑定颜色



我有一个关于swiftUI中可选绑定的问题。我有一个结构体:

struct LightPairing: View {
@Binding var light: Color?
init(light: Binding<Color?>) {
self._light = light
}
// the rest of the code, such as body is omitted since it is very long
}

我想给light属性一个默认值nil, light: Binding<Color?>= nil,但它不起作用。有什么办法可以绕过这个问题吗?

编辑:当我做的时候:

light: Binding<Color?> = nil我得到错误消息说

"Nil默认参数值不能转换为类型"Binding<颜色?";>

你的属性类型是Binding<Color?>,所以你不能简单地分配nil。您必须在绑定值为nil的地方分配Binding<Color?>

你可以通过Binding.constant():

struct LightPairing: View {
@Binding var light: Color?
init(light: Binding<Color?> = .constant(nil)) {
self._light = light
}
// the rest of the code, such as body is omitted since it is very long
}

现在,如果您不为light提供绑定,则会为您提供默认值。

@Binding从另一个属性中获取值,例如@State属性包装器(拥有该值的属性)。

您可以从另一个结构体(其他地方)的属性设置@Binding

@State private var lightElsewhere: Color? = nil

然后调用……

LightPairing(light: $lightElsewhere)

或者将@Binding更改为该结构体中的State属性。

@State private var light: Color? = nil

发生在哪里取决于你的应用逻辑。

尝试如下:-

struct ContentView: View {

var body: some View {
LightPairing(light: .constant(nil))
}
}
struct LightPairing: View {
@Binding var light: Color?
init(light: Binding<Color?>) {
self._light = light
}
var body: some View {
ZStack {
//Some Code
}
}
// the rest of the code, such as body is omitted since it is very long
}

最新更新