Reputation: 1046
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.
Upvotes: 4
Views: 1070
Reputation: 257533
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)
}
}
}
Upvotes: 5