TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Name not printable in the MainView

Forums > SwiftUI

I am trying to print the content of a text field from a secondary view in the main view, but to no success. Currently the output is nil.

struct MainView: View {
     @ObservedObject var viewModel = MainViewModel()
     var body: some View{
         HStack{
              SecondaryView()
              Button(action: {
                  print("\(viewModel.name)") // nil
              }), label: {
                  Text("Print name")
              }
         }
     }
}  

struct SecondaryView: View {
        @ObservedObject var viewModel = MainViewModel()
        var body: some View{
             NameTextfield(text: $viewModel.name, placeholder: Text("Name…"))
        }
}

Why is the name lost in the MainView? How can I persist the name?

2      

You are creating two different MainViewModel objects, so when you read viewModel.name in your MainView, it's not the same value as viewModel.name in SecondaryView. Instead, you should create one MainViewModel object in MainView as a @StateObject and then pass it to the SecondaryView for use as an @ObservedObject so that the same object is used in both Views.

Like this:

struct MainView: View {
     @StateObject var viewModel = MainViewModel()
     var body: some View{
         HStack{
              SecondaryView(viewModel: viewModel)
              Button(action: {
                  print("\(viewModel.name)")
              }), label: {
                  Text("Print name")
              }
         }
     }
}  

struct SecondaryView: View {
        @ObservedObject var viewModel: MainViewModel
        var body: some View{
             NameTextfield(text: $viewModel.name, placeholder: Text("Name…"))
        }
}

2      

Ah, now I get the problem. It works. Thank you @roosterboy.

2      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.