SecureTextField
in SwiftUI resets its content after dismissing the keyboard.
This behavior is not observed with the regular TextField
. When typing in the SecureTextField
and then dismissing the keyboard, any entered text is lost upon resuming typing. This behavior is unexpected and inconsistent with the behavior of other text input fields in SwiftUI.
How can I prevent the SecureTextField
from resetting its content after keyboard dismissal, ensuring that the entered text persists as expected?
struct PasswordTextField: View {
var placeHolder:String
var image:String?
var label:String
@Binding var text:String
@FocusState private var isTextFieldFocused:Bool
var body: some View {
VStack(alignment: .leading,spacing: 4) {
if !label.isEmpty {
Text(label).customFont(Font.poppinsMedium, size: 15)
.foregroundStyle(Color.appTextBlackColor)
}
HStack {
SecureField("", text: $text)
.placeholder(when: text.isEmpty, placeholder: {
Text(placeHolder).foregroundStyle(Color.appPlaceholderColor)
})
.focused($isTextFieldFocused)
.autocorrectionDisabled(true)
.textInputAutocapitalization(.none)
.font(.custom(Font.poppinsMedium, size: 14))
.foregroundStyle(Color.appTextBlackColor)
.padding([.leading],16)
.frame(height: 45)
if let image {
Image(image)
.resizable()
.scaledToFit()
.foregroundStyle(Color.appBorderColor)
.padding()
}
}
.frame(height: 50)
.background(
RoundedRectangle(cornerSize: CGSize(width: 8, height: 8))
.stroke(isTextFieldFocused ? Color.appPinkColor : Color.appBorderColor,lineWidth: 2)
)
}
.foregroundStyle(Color.appPlaceholderColor)
.onTapGesture {
isTextFieldFocused = true
}
}
}
@State private var password:String = ""
VStack(spacing:20){
CustomTextField(placeHolder: "Phone Number", image: "mobile", label: "Phone", text: $phone)
.keyboardType(.numberPad)
.onChange(of: phone) { newValue in
if newValue.count >= 10 {
UIApplication.shared.endEditing()
phone = String(newValue.prefix(10))
}
}
PasswordTextField(
placeHolder: "Password",
image: "password",
label: "Password",
text: $password
)
} .onTapGesture {
UIApplication.shared.endEditing()
}