3

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.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Shivani Bajaj
  • 996
  • 10
  • 23
  • Does this answer your question? [SwiftUI: How to make TextField become first responder?](https://stackoverflow.com/questions/56507839/swiftui-how-to-make-textfield-become-first-responder) – mahan Aug 02 '21 at 11:52
  • You can listen to the `isFirstResponder` property – mahan Aug 02 '21 at 11:52

1 Answers1

4

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

demo

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)
        }
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • 2
    this is a iOS 15 feature and my app has the minimum target of 14.1. Could you help in that? – Shivani Bajaj Aug 01 '21 at 10:12
  • I faced the same issue. I found that listening for keyboard updates in a viewModel as a proxy for textfield focusing was a fair solution. may not apply in your case ... – Gautier Aug 08 '22 at 18:09