我有2个文本字段...
TextField("Username", text: $viewModel.usernameStore){}
.padding(.all, 8)
.background(Color(red:0.5, green: 0.5, blue: 0.5, opacity: 0.3))
.cornerRadius(4.0)
.padding(.bottom, 5)
SecureField("Password", text: $viewModel.passwordStore){}
.padding(.all, 8)
.background(Color(red:0.5, green: 0.5, blue: 0.5, opacity: 0.3))
.cornerRadius(4.0)
.padding(.bottom, 5)
还有一个将它们全部清除的函数...
func clearCredentials(){
$viewModel.usernameStore.wrappedValue = ""
$viewModel.passwordStore.wrappedValue = ""
}
调用该函数并清除文本字段时,将重新填充密码的占位符,但不填充用户名的占位符,只会清除它。
我假设这与密码是安全字段有关。 清除后如何获取用户名以重新填充占位符文本?
答案 0 :(得分:2)
我认为这是一个SwiftUI错误,因为如果您点击其他字段,则占位符会再次出现...
我为您提供了另一种解决方案(这是Apple清除文本字段的标准方法,因此用户知道如何处理...
检查一下:
struct CustomTextField: UIViewRepresentable {
class Coordinator: NSObject, UITextFieldDelegate {
@Binding var text: String
init(text: Binding<String>) {
_text = text
}
func textFieldDidChangeSelection(_ textField: UITextField) {
text = textField.text ?? ""
}
}
@State var secure : Bool
@State var initialText : String
@Binding var text: String
@State var placeholder : String
func makeUIView(context: UIViewRepresentableContext<CustomTextField>) -> UITextField {
let textField = UITextField(frame: .zero)
textField.placeholder = placeholder
textField.delegate = context.coordinator
textField.text = initialText
textField.clearButtonMode = .always
textField.isSecureTextEntry = secure
return textField
}
func makeCoordinator() -> CustomTextField.Coordinator {
return Coordinator(text: $text)
}
func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<CustomTextField>) {
uiView.text = text
uiView.placeholder = placeholder
}
}
struct ContentView: View {
@State var username : String = ""
@State var password : String = ""
func clearCredentials(){
username = ""
password = ""
}
var body: some View {
VStack {
CustomTextField(secure: false, initialText: "", text: $username, placeholder: "Username")
.fixedSize()
.padding(.all, 8)
.background(Color(red:0.5, green: 0.5, blue: 0.5, opacity: 0.3))
.cornerRadius(4.0)
.padding(.bottom, 5)
CustomTextField(secure: true, initialText: "", text: $password , placeholder: "Password")
.fixedSize()
.padding(.all, 8)
.background(Color(red:0.5, green: 0.5, blue: 0.5, opacity: 0.3))
.cornerRadius(4.0)
.padding(.bottom, 5)
Button(action: {
self.clearCredentials()
}) {
Text("Clear credentials")
}
}.padding()
}
}
答案 1 :(得分:0)
SwiftUI的TextField就像UITextField一样支持占位符文本-灰色文本,空白时显示在文本字段中,或者使用提示(“输入密码”)或显示一些示例数据。
要设置占位符,请将其作为文本字段的初始化程序的一部分传入,如下所示:
struct ContentView: View {
@State private var emailAddress = ""
var body: some View {
TextField("johnnyappleseed@apple.com", text: $emailAddress)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
}
}