Farshid roohi
Farshid roohi

Reputation: 768

How to get textField values in the list swiftui

I used the list this way I want to send all TextField values when the submit button is clicked.

My problem is that I can't get the TextField value in the list

I also use mvvm architecture in the project

my code in the project :

My Model :

import Foundation
import SwiftUI

struct MyModel : Identifiable {
    var id:Int64
    var title:String
   @State var value:String
}

My ViewModel :

import Foundation
import SwiftUI


class MyViewModel: ObservableObject {
    @Published var items:[MyModel] = []

    init() {
        populateItem()
    }

    func populateItem(){
        self.items.append(MyModel(id: 0, title: "title #1", value: ""))
        self.items.append(MyModel(id: 1, title: "title #2", value: ""))
        self.items.append(MyModel(id: 2, title: "title #3", value: ""))
        self.items.append(MyModel(id: 3, title: "title #4", value: ""))
        self.items.append(MyModel(id: 4, title: "title #5", value: ""))
        self.items.append(MyModel(id: 5, title: "title #6", value: ""))
    }

}

My View :

import SwiftUI

struct ContentView: View {

    @ObservedObject var myViewModel = MyViewModel()

    var body: some View {
        VStack {

            List {
                ForEach(self.myViewModel.items) {item in
                    HStack {
                        Text(item.title)
                        TextField("value", text: item.$value)
                    }
                }
            }

            Button(action: {
                print(self.myViewModel.items[0].value)
            }){
                Text("Submit")
            }.padding()
        }
    }
}

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

Upvotes: 1

Views: 2343

Answers (1)

Aleksey Potapov
Aleksey Potapov

Reputation: 3783

First remove @State property wrapper from your model's value property. And update your ForEach with the next code:

ForEach(self.myViewModel.items.indices, id:\.self) { index in
    HStack {
        Text(self.myViewModel.items[index].title)
        TextField("value", text: Binding(
            get: {
                return self.myViewModel.items[index].value
        },
            set: { newValue in
                return self.myViewModel.items[index].value = newValue
        }))
    }
}

Upvotes: 3

Related Questions