SwiftUI 中的 ForEach TextField

2024-01-01

假设我有一堂课Student

class Student: Identifiable, ObservableObject {
    var id = UUID()

    @Published var name = ""
}

在另一个类的数组中使用(称为Class)

class Class: Identifiable, ObservableObject {
    var id = UUID()

    @Published var name = ""
    var students = [Student()]
}

在我的中是这样定义的View.

@ObservedObject var newClass = Class()

我的问题是:我怎样才能创建一个TextField对于每个Student并将其与name属性是否正确(没有错误)?

ForEach(self.newClass.students) { student in
    TextField("Name", text: student.name)
}

现在,Xcode 向我抛出这个:

Cannot convert value of type 'TextField<Text>' to closure result type '_'

我尝试添加一些$s 在调用变量之前,但它似乎不起作用。


只需更改@Published into a @State对于学生的姓名属性。@State是给你一个Binding$ prefix.

import SwiftUI

class Student: Identifiable, ObservableObject {
  var id = UUID()

  @State var name = ""
}

class Class: Identifiable, ObservableObject {
  var id = UUID()

  @Published var name = ""
  var students = [Student()]
}

struct ContentView: View {
  @ObservedObject var newClass = Class()

  var body: some View {
    Form {
      ForEach(self.newClass.students) { student in
        TextField("Name", text: student.$name) // note the $name here
      }
    }
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
  }
}

一般来说,我还建议使用结构而不是类。

struct Student: Identifiable {
  var id = UUID()
  @State var name = ""
}

struct Class: Identifiable {
  var id = UUID()

  var name = ""
  var students = [
    Student(name: "Yo"),
    Student(name: "Ya"),
  ]
}

struct ContentView: View {
  @State private var newClass = Class()

  var body: some View {
    Form {
      ForEach(self.newClass.students) { student in
        TextField("Name", text: student.$name)
      }
    }
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SwiftUI 中的 ForEach TextField 的相关文章

随机推荐