我有两个类SubmitPhoneView和VerifyPhoneView。
由于某种原因,我注意到每当我在SubmitPhoneView的文本字段中输入数字时,它就会调用VerifyPhoneView的init方法。我希望只调用一次(当我按下SubmitPhoneView上的“继续”按钮时)
为什么会这样?
SubmitPhoneView类:
import SwiftUI
import Firebase
struct SubmitPhoneView: View {
@State private var phoneNumber: String = ""
@State private var verificationID : String = ""
@State private var presentMe = false
var body: some View {
ZStack {
Text("My number is")
HStack(spacing: 20){
Text("+1")
TextField("Enter phone number", text: $phoneNumber)
.keyboardType(.numberPad)
}
VStack {
NavigationLink(destination: VerifyPhoneView(phoneNumber: $phoneNumber.wrappedValue, verificationID: $verificationID.wrappedValue), isActive: $presentMe) { EmptyView() }
Button(action: {
self.submitPhoneNumber()
self.presentMe = true
}) {
Text("Continue")
}
}
}
func submitPhoneNumber() {
PhoneAuthProvider.provider().verifyPhoneNumber("+1" + phoneNumber, uiDelegate: nil) { (verificationID, error) in
if error != nil {
print(error.debugDescription)
return
}
else {
self.verificationID = verificationID!
}
}
}
}
VerifyPhoneView类:
import SwiftUI
import Firebase
struct VerifyPhoneView: View {
private var phoneNumber: String
@State private var verificationID: String
@State private var verificationCode: String = ""
@State private var loginSuccesful: Bool = false
@EnvironmentObject var ls: LoginStatus
@EnvironmentObject var currentUser: CurrentUser
init(phoneNumber: String, verificationID: String) {
print("the init method was called for VerifyPhoneView")
self.phoneNumber = phoneNumber
_verificationID = State(initialValue: verificationID)
print(self.verificationID)
}
var body: some View {
ZStack {
Text("My code is")
TextField("Enter code", text: $verificationCode)
Button(action: {
self.submitVerificationCode()
}) {
Text("Continue")
}
}
}
func submitPhoneNumber() {
// doesn't matter
}
func submitVerificationCode() {
// doesn't matter
}
}
}
答案 0 :(得分:1)
使用DeferView,如下所示
VStack {
NavigationLink(destination: DeferView {
VerifyPhoneView(phoneNumber: $phoneNumber.wrappedValue, verificationID: $verificationID.wrappedValue)
}, isActive: $presentMe) { EmptyView() }
Button(action: {
self.submitPhoneNumber()
self.presentMe = true
}) {
Text("Continue")
}