I am trying to pass a value from my View LingView, to another View ContentView. I have a state variable in the login view as such:
@State var userName: String = ""
@State private var password: String = ""
I then pass the value from the Content View Constructor in two places: This is in RootView
var body: some View {
ContentView(userName: LoginView().$userName)
.fullScreenCover(isPresented: $authenticator.needsAuthentication) {
LoginView()
.environmentObject(authenticator) // see note
}
}
This is in Content View:
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(userName: Login().$userName)
.environmentObject(Authenticator())
}
}
I want to use the variable to pass into the getPictures() function that a database file uses. I am kind of confused as to what I am suppose to do. The parent view in this case would be LoginView correct? I am unsure why I keep getting: Cannot find type 'userName' in scope.
@Binding var userName: String
print(userName)
var pictureURL = DbHelper().getPictures()
After running the following code. I understand that you should make state private to a View, but in this case how would I pass the state value to the content view? The LoginView does not call the ContentView directly. Maybe I don't understand Bindings and State, but I have read this article: https://learnappmaking.com/binding-swiftui-how-to/
CodePudding user response:
You are initialising two separate login views. The username binding passed to ContentView
is therefore a different binding to the one you have under .fullscreenCover
To make it work, you can declare a State
variable in RootView
,
@State private var userName: String = "" // In RootView
then pass its binding to both ContentView
and LoginView
.
@Binding var userName: String // In ContentView and LoginView
Simply put, State
holds your actual username value, while Binding
gives you a method of seeing and changing it from somewhere else.