无法将“Binding<String>”类型的值分配给“String”类型

use*_*170 14 ios swift swiftui

我收到以下错误:

无法将“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 = "" }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Hun*_*ion 40

代替:

self.text = $text

和:

self._text = text

您需要将 的值注入text到 的包装值中self.text。下划线“打开”绑定,以便您更改其包装值。不需要$在初始化程序中使用。

  • 遗憾的是,如果您选择“生成成员初始化程序”,它无法为“绑定”变量创建正确的 inti。 (2认同)