总的来说,我有一个具有 @Published 变量的 ViewModel
class Parent : ObservableObject{
@Published var email_SignUp = ""
@Published var password_SignUp = ""
@Published var reEnterPassword = ""
}
另外,我有一个视图,用户可以通过文本字段进行交互。在这里,我使用了一个自制的自定义 TextFields,它以图像、文本和动作为参数。
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 只是与“email_SignUp”和“password_SignUp”无关的其他按钮的视图。
struct TestView: View {
@ObserverObject var model: Parent
var body: some View {
...(some actions with others variables of model)
}
}
这是我的自定义 TextField 的样子 -
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)
}
}
在文本字段中输入数据时, - ViewModel 中的“email_SignUp”不为空,但是,在点击 NavigationLink“Next”后,ViewModel 类“Parent”中的 email_SignUp 变为空......我该怎么办?