0

I am trying to set a default text on a TextView when the view appears, while being able to still keep track of changes to the TextView that I can then pass on to my ViewModel.

Here is a little example that looks like what I am trying to do. This does however not work, it does not update the state as I would have expected. Am I doing something wrong?

struct NoteView: View {
    
    @State var note = ""
    
    var noteFromOutside: String?
    
    var body: some View {
        VStack {
            TextField("Write a note...", text: $note)
                .onSubmit {
                    //Do something with the note.
                }
        }
        .onAppear {
            if let newNote = noteFromOutside {
                note = newNote
            }
        }
    }
}

struct ParentView: View {
    var note = "Note"
    
    var body: some View {
        VStack {
            NoteView(noteFromOutside: note)
        }
    }
}
bjorn.lau
  • 774
  • 5
  • 16
  • Under what circumstances are you expecting the state to be updated? When `noteFromOutside` changes (which isn't represented in your example)? Maybe you're looking for `onChange` rather than `onAppear`? – jnpdx Mar 09 '22 at 21:50
  • The NoteView is nested inside 2 other views, one of them will have a "note" and the other one will not. So I am trying to check when the view Appears if the was called with a string or nil and then based on that set the text in the TextView. But in general, if I just want to use "NoteView" and always give it a vaild string, I still can't figure out how to set the state variable in TextView. – bjorn.lau Mar 09 '22 at 21:59
  • If I just do: if let note = note { Text(note) } in my VStack it works perfectly. So maybe my question is more on how to set this TextField "text" when I call my NoteView. – bjorn.lau Mar 09 '22 at 22:04
  • I have updated the question code to be more precise :) – bjorn.lau Mar 09 '22 at 22:13
  • Welp... If I run my new example it works. So... I guess some other code in my real project prevents this from happening. – bjorn.lau Mar 09 '22 at 22:18
  • That is part of the reason to do a [Minimal, Reproducible Example (MRE)](https://stackoverflow.com/help/minimal-reproducible-example). Often, you solve your own problem, or at least find out where you problem is not... – Yrb Mar 09 '22 at 23:09
  • Indeed! Thanks for the help, you have pointed me in the right direction every time somehow :) – bjorn.lau Mar 10 '22 at 00:55
  • view model is the wrong approach https://stackoverflow.com/a/60883764/259521 – malhal Mar 10 '22 at 15:20

1 Answers1

0

Found this answer to another post which solved my problem. The key was in the @Binding and init().

https://stackoverflow.com/a/64526620/12764203

bjorn.lau
  • 774
  • 5
  • 16