Overall, I have a ViewModel which has @Published vars
class Parent : ObservableObject{
@Published var email_SignUp = ""
@Published var password_SignUp = ""
@Published var reEnterPassword = ""
}
Also, I have a View where user make interactions through textfield. Here, I used a self-made custom TextFields which take image, text and action as a parameters.
import SwiftUI
struct SignUpViewParent : View {
@ObservedObject var model: Parent
let settings = Settings()
var body: some View{
VStack(spacing: 20){
CustomTextField(image: "person", placeHolder: "Email", txt: $model.email_SignUp).autocapitalization(.none)
CustomTextField(image: "lock", placeHolder: "Password", txt: $model.password_SignUp)
CustomTextField(image: "lock", placeHolder: "Re-Enter", txt: $model.reEnterPassword)
NavigationLink(destination: TestView(model: Parent())) {
HStack {
Spacer()
Text("Next")
.frame(width: 90,height: 50).padding(.trailing, 50)
.cornerRadius(24)
.foregroundColor(.init(red: 50, green: 50, blue: 50))
.background(Color.init(#colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)))
.buttonStyle(PlainButtonStyle.init())
.cornerRadius(24)
}.padding(.trailing)
.padding(.bottom)
}
}
}
}
TestView is just View with other buttons not related to 'email_SignUp' and 'password_SignUp'.
struct TestView: View {
@ObserverObject var model: Parent
var body: some View {
...(some actions with others variables of model)
}
}
Here is how my custom TextField looks like -
import SwiftUI
struct CustomTextField : View {
var image : String
var placeHolder : String
@Binding var txt : String
var body: some View{
ZStack(alignment: Alignment(horizontal: .leading, vertical: .center)) {
Image(systemName: image)
.font(.system(size: 24))
.foregroundColor(Color.black)
.frame(width: 60, height: 60)
.background(Color.white)
.clipShape(Circle())
ZStack{
if placeHolder == "Password" || placeHolder == "Re-Enter"{
SecureField(placeHolder, text: $txt)
}
else{
TextField(placeHolder, text: $txt)
}
}
.padding(.horizontal)
.padding(.leading,65)
.frame(height: 60)
.background(Color.white.opacity(0.2))
.clipShape(Capsule())
}
.padding(.horizontal)
}
}
While entering the data in textfield, - "email_SignUp" in ViewModel is not empty, however, after tapping on the NavigationLink "Next", email_SignUp in ViewModel class "Parent" becomes empty... What should I do?
You pass into navigation link destination new instance of
Parent
, but if you want use already entered values, you should pass local property, like