SwiftUI:如何在ListView中使用绑定变量

时间:2020-09-08 19:22:29

标签: swiftui

我正在尝试使用ListView来显示TextField,用户可以在其中使用绑定变量输入名称。但是我遇到了错误。

此代码显示一个人的作品:

import SwiftUI

struct Person {
  var firstName: String
  var lastName: String
}

class People: ObservableObject {
  @Published var people = [
    Person(firstName: "Joe", lastName: "Smith"),
    Person(firstName: "George", lastName: "Todd"),
    Person(firstName: "Emily", lastName: "Wallace"),
    Person(firstName: "Jeffrey", lastName: "Dodd"),
    Person(firstName: "Donny", lastName: "Joseph"),
    Person(firstName: "Mark", lastName: "Ryan"),
    Person(firstName: "Cindy", lastName: "Geller"),
    Person(firstName: "Teresa", lastName: "Kelly"),
  ]
}

struct Basic: View {
  
  @ObservedObject var people = People()
  
    var body: some View {
      VStack {
        Text("My name is \(people.people[1].firstName) \(people.people[1].lastName)")
            HStack {
              TextField("First name", text: $people.people[1].firstName)
              TextField("Last name", text: $people.people[1].lastName)
            }
      }
      .padding()
    }
}

但是,当我尝试将此编码放入列表中时,会出现错误。这是我正在使用的编码:

struct Person {
  var firstName: String
  var lastName: String
}

class People: ObservableObject {
  @Published var people = [
    Person(firstName: "Joe", lastName: "Smith"),
    Person(firstName: "George", lastName: "Todd"),
    Person(firstName: "Emily", lastName: "Wallace"),
    Person(firstName: "Jeffrey", lastName: "Dodd"),
    Person(firstName: "Donny", lastName: "Joseph"),
    Person(firstName: "Mark", lastName: "Ryan"),
    Person(firstName: "Cindy", lastName: "Geller"),
    Person(firstName: "Teresa", lastName: "Kelly"),
  ]
}


struct InListView: View {
  
  @ObservedObject var people = People()
  
    var body: some View {
      List(people.people, id:\.firstName) { name in
        VStack {
          Text("My name is \(name.firstName) \(name.lastName)")
              HStack {
                TextField("First name", text: $name.firstName)
                TextField("Last name", text: $name.lastName)
              }
        }
        .padding()
      }
    }
}

在两个TextField上发生错误。该错误显示“在范围内找不到'$ name'”。

如何在ListView中使用绑定变量?

谢谢。

1 个答案:

答案 0 :(得分:0)

这是一个可能的解决方案

struct InListView: View {
    
    @ObservedObject var people = People()
    
    var body: some View {
        List(0..<people.people.count, id:\.self) { i in
            VStack {
                Text("My name is \(people.people[i].firstName) \(people.people[i].lastName)")
                HStack {
                    TextField("first name", text: $people.people[i].firstName)
                    TextField("first name", text: $people.people[i].lastName)
                }
            }
            .padding()
        }
    }
}