'How do I store the Input of a Textfield and display it in another View in Swift UI?

I am just learning to code and I have a question. How do I store the Input data of a Textfield and display it in another View? I tried it with Binding but it doesn't work that way. I appreciate your help

import SwiftUI

struct SelectUserName: View {
    
    @Binding var name: String
    
    var body: some View {
        TextField("Name", text: self.$name)
    }
}


struct DisplayUserName: View {
    
    @State private var name = ""
    
    var body: some View {
        // the name should be diplayed here!
        Text(name)
    }
}

struct DisplayUserName_Previews: PreviewProvider {
    static var previews: some View {
        DisplayUserName()
    }
}


Solution 1:[1]

State should always be stored in a parent and passed down to the children. Right now, you're not showing the connection between the two views (neither reference the other), so it's a little unclear how they relate, but there are basically two scenarios:

Your current code would work if DisplayUserName was the parent of SelectUserName:

struct DisplayUserName: View {
    
    @State private var name = ""
    
    var body: some View {
        Text(name)
        SelectUserName(name: $name)
    }
}

struct SelectUserName: View {
    
    @Binding var name: String
    
    var body: some View {
        TextField("Name", text: self.$name)
    }
}

Or, if they are sibling views, the state should be stored by a common parent:

struct ContentView  : View {
    @State private var name = ""
    
    var body: some View {
        SelectUserName(name: $name)
        DisplayUserName(name: name)
    }
}

struct SelectUserName: View {
    
    @Binding var name: String
    
    var body: some View {
        TextField("Name", text: self.$name)
    }
}


struct DisplayUserName: View {
    
    var name : String //<-- Note that @State isn't needed here because nothing in this view modifies the value
    
    var body: some View {
        Text(name)
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jnpdx