Learn Courses My Dashboard

TextField in super view to collect data for parents view model

I want to create a super view that will modify the parent view model’s string using TextField.

First I define the view model which contains the name to modify.

import SwiftUI

class NameViewModel: ObservableObject {
    var name: String = ""
    var comment: String = ""
}

The view for writing a line header over a TextField

struct TextFieldAndTitle: View {

    var title: String
    var prompt: String
    @Binding var theName: String

    var body: some View {
        VStack(alignment: .leading) {
            Text(title)
                .font(.caption)
                .padding(.bottom, 1.0)
            
            TextField("First, Last", text: $theName)
                .textFieldStyle(.roundedBorder)
        }
    }
}

The ContentView calls TextFieldWithTitle() to modify the name string in the NameViewModel object.

struct ContentView: View {
    @StateObject var nameVM: NameViewModel = NameViewModel()
    
    var body: some View {
        
        VStack( alignment: .leading) {
            TextFieldAndTitle(title: "Name",
                              prompt: "First Last",
                              theName: $nameVM.name)
            
            Text("The name is: \(nameVM.name)")
                .foregroundColor(Color.blue)
                .font(.caption)
                
        }
        .padding()
    }
}

When I modify the string in the TextFieldAndTitle the updated data does not appear in the nameVM.name property. What am I doing wrong?

I just realized why it was not working. I made this modification and it worked.

class NameViewModel: ObservableObject {
@Published var name: String = “”
@Published var comment: String = “”
}