Home > Software design >  How to pass value form view to view model in SwiftUI?
How to pass value form view to view model in SwiftUI?

Time:11-01

I am having one email filed in view, that value I want to pass to viewModel. But I am not sure how.

Email View

import SwiftUI
    
struct EmailView: View {
    
    @State private var email: String = ""

    init(viewModel:EmailViewModel) {
        self.viewModel = viewModel
    }
    TextField("", text: $email)
    func sendButtonAction() {
        viewModel.updateDataToServer()
    }
 }

Email Viewmodel

import Foundation
import SwiftUI

class EmailViewModel: NSObject, ObservableObject {

    var emailText = ""

    convenience init(emailText: String) {
        self.init()
        self.emailText = emailText
    }

    func updateDataToServer() {
        print("Show email text"   emailText). // not getting email value here???
    }
}

I am coming to email screen from other screen. How should I pass email value form here?

NavigationLink(destination: EmailView(viewModel: EmailViewModel(emailText: "")), isActive: $pushToMail) {
    EmptyView()
}.hidden()

CodePudding user response:

Try this type of approach as shown in the example code:

import SwiftUI

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {
    @StateObject var emailModel = EmailViewModel()

    var body: some View {
        NavigationView {
            VStack (spacing: 55) {
                NavigationLink(destination: EmailView(viewModel: emailModel)) {
                    Text("go to EmailView")
                }
                Text("email was: \(emailModel.emailText)")
            }
        }.navigationViewStyle(.stack)
    }
}

class EmailViewModel: ObservableObject {
    @Published var emailText = ""
    
    func updateDataToServer() {
        print("----> Show email text "   emailText)
    }
}

struct EmailView: View {
    @ObservedObject var viewModel: EmailViewModel
    
    var body: some View {
        TextField("Enter your email", text: $viewModel.emailText).border(.green)
            .onSubmit {
                viewModel.updateDataToServer()
            }
    }
}
  • Related