I want to know, how can we detect if a SecureTextField has lost focus or gained one.
Currently I am using tap gesture to check if focus is gained and change border color accordingly, but sometimes color changes but editing does not start.
SecureField("Password", text: $viewModel.password) {
passwordEditingState = .ended
focusedTextField = nil
}
.onTapGesture {
focusedTextField = TextFields.password.rawValue
}
.padding(20)
.background(Color.systemDefaultSecondary)
.cornerRadius(16.0)
.disableAutocorrection(true)
.autocapitalization(.none)
.overlay(RoundedRectangle(cornerRadius: 16).stroke(isSelected ? Color.green : Color.gray, lineWidth: 1))
One thing to consider that my app has minimum target of 14.1 so I need a solution based upon that.
You can use focused modifier with FocusState, like below.
Demo prepared & tested with Xcode 13 / iOS 15.
Note: you need Simulator or real device - it does not work in Preview

struct ContentView: View {
@FocusState var isInFocus: Bool
@State private var text: String = "password"
var body: some View {
VStack {
if isInFocus {
Text("Field is in focus!")
}
SecureField("Password", text: $text)
.focused($isInFocus)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With