我得到以下错误:
无法将"Binding"类型的值分配给"String"类型
如何修复?请帮忙。
struct TextFieldWithClear: View {
var title: String
@Binding var text: String
init(_ title: String, text: Binding<String>) {
self.title = title
self.text = $text // ERROR: Cannot assign value of type 'Binding<String>' to type 'String'
}
var body: some View {
HStack {
TextField("Title", text: $text)
Image(systemName: "xmark.circle.fill")
.onTapGesture { text = "" }
}
}
}
替换:
self.text = $text
带有:
self._text = text
您需要将text
的值注入到self.text
的封装值中。下划线";打开";绑定,以便更改其包装的值。不需要在初始化器中使用$
。
struct TextFieldWithClear: View {
let title: String
@Binding var text: String
var body: some View {
HStack {
TextField("Title", text: $text)
Image(systemName: "xmark.circle.fill")
.onTapGesture { text = "" }
}
}
}