如何为带有@Binding的SwiftUI View编写自定义init初始化函数?
为带@Binding属性的Swift View编写自定义初始化函数
先看一段可正常运行的代码:
struct DetailView: View { var counter: Binding<Int> init(counter: Binding<Int>) { self.counter = counter } var body: some View { Text("counter: \(counter)") } } struct ContentView: View { @State var counter = 1 var body: some View { DetailView(counter: $counter) } }
当把属性改为使用@Binding包装器后,自定义的init函数无法编译:
struct DetailView: View { @Binding var counter: Int init(counter: Binding<Int>) { self.counter = counter } var body: some View { Text("counter: \(counter)") } }
报错信息:
Cannot assign value of type 'Binding
' to type 'Int'
但移除自定义init函数后,代码又能正常运行:
struct DetailView: View { @Binding var counter: Int var body: some View { Text("counter: \(counter)") } }
解决方案
@Binding是Swift的属性包装器,它会自动生成一个以下划线开头的底层存储属性(比如_counter),这个属性的类型才是Binding<Int>。所以在自定义初始化函数中,你需要给这个底层存储属性赋值,而不是直接给包装后的属性赋值:
struct DetailView: View { @Binding var counter: Int init(counter: Binding<Int>) { self._counter = counter } var body: some View { Text("counter: \(counter)") } }
这样修改后,代码就能正常编译运行了。如果需要自定义初始化参数的名称,也可以灵活调整,比如:
struct DetailView: View { @Binding var counter: Int init(value: Binding<Int>) { self._counter = value } var body: some View { Text("counter: \(counter)") } } // 使用时 DetailView(value: $counter)
内容的提问来源于stack exchange,提问作者OMGPOP
相关产品推荐
相关产品推荐

