UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.