SwiftUI text field text color issue

Viewed 1490

I am facing issues with TextField (color of the text being input). I am using MVVM pattern and my code is as below:


import SwiftUI

struct ContentView: View {
    @ObservedObject var viewModel: ViewModel

    var body: some View {
        CustomView(email: $viewModel.dataModel.emailID)
    }
}

struct CustomView: View {
    
    @Binding var email: String
        
    var body: some View {
        VStack {
            
            TextField("email", text: $email)
                .foregroundColor(.black)
                .frame(height: 30.0)
                .textContentType(.emailAddress)
                .keyboardType(.emailAddress)
                .background(Color.white)
                .padding([.top, .bottom])
            Spacer()
        }.padding(20)
    }
}


public final class ViewModel: ObservableObject {
    
    /// data model
    public var dataModel: DataModel
    
    public init (model: DataModel) {
        self.dataModel = model
    }
    
}
public final class DataModel {
    
    @Published public var emailID: String
    
    public init(emailID: String) {
        self.emailID = emailID
    }
}

The exact issue is that with the above code, when I type a text into the text field, the text color is also white which is the same as the background color, though the foreground color is black. Please tell me where I am going wrong. I am instantiating the ContentView from SceneDelegate as follows:


let contentView = ContentView(viewModel: ViewModel(model: DataModel(emailID: "")))

1 Answers

You have broken chain of binding. Here is fixed code (note that some inits changed!):

struct ContentView: View {
    @ObservedObject var viewModel: ViewModel

    var body: some View {
        CustomView(model: viewModel.dataModel)
    }
}

struct CustomView: View {

    @ObservedObject var model: DataModel

    var body: some View {
        VStack {

            TextField("email", text: $model.emailID)
                .foregroundColor(.black)
                .frame(height: 30.0)
                .textContentType(.emailAddress)
                .keyboardType(.emailAddress)
                .background(Color.white)
                .padding([.top, .bottom])
            Spacer()
        }.padding(20)
    }
}


public final class ViewModel: ObservableObject {

    /// data model
    public var dataModel: DataModel

    public init (model: DataModel) {
        self.dataModel = model
    }

}

public final class DataModel: ObservableObject {

    @Published public var emailID: String

    public init(emailID: String) {
        self.emailID = emailID
    }
}
Related