简体   繁体   中英

How to pass value form view to view model in SwiftUI?

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()

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()
            }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM