struct CustomUIKitTextField: UIViewRepresentable {
@Binding var text: String
var placeholder: String
func makeUIView(context: UIViewRepresentableContext<CustomUIKitTextField>) -> UITextField {
let textField = UITextField(frame: .zero)
textField.delegate = context.coordinator
textField.placeholder = placeholder
return textField
}
func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<CustomUIKitTextField>) {
uiView.text = text
uiView.setContentHuggingPriority(.defaultHigh, for: .vertical)
uiView.setContentCompressionResistancePriority(.required, for: .vertical)
}
func makeCoordinator() -> CustomUIKitTextField.Coordinator {
Coordinator(parent: self)
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: CustomUIKitTextField
init(parent: CustomUIKitTextField) {
self.parent = parent
}
func textFieldDidChangeSelection(_ textField: UITextField) {
parent.text = textField.text ?? ""
}
}
}
该应用的第一个屏幕有一个“使用电子邮件登录”按钮,点击后会显示 MailView。MailView 中包含一个名为 CustomUIKitTextField
的文本框,并使用 @Published
属性作为 ObservableObject
视图模型的文本框文本。
struct MailView: View {
@ObservedObject var viewModel: MailSignUpViewModel
var body: some View {
VStack {
CustomUIKitTextField(placeholder: self.viewModel.placeholder,
text: self.$viewModel.mailAddress)
.padding(.top, 30)
.padding(.bottom, 10)
NavigationLink(destination: UsernameView(viewModel: UsernameSignUpViewModel())) {
Text("Next")
}
Spacer()
}
}
}
一切都很顺利,直到我推出另一个视图(例如UsernameView)如MailView。它的实现方式完全相同,但是不知怎么地,CustomUIKitTextField
在我完成输入后会收到一个空字符串的updateUIView
调用。
还有其他奇怪的行为,例如将MailView和UsernameView包装在另一个NavigationView中时,一切正常。但这显然不是解决问题的方法,因为那样就会有多个NavigationView。
如果在视图模型中使用@State属性而不是@Published属性,也可以正常工作。但我不想使用@State,因为我真的希望保持模型代码与视图分离。
是否有人遇到过同样的问题或类似的问题?