Shivani Bajaj
Shivani Bajaj

Reputation: 1046

How to know when a SecureTextField in SwiftUI has gained focus or lost focus?

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

Answers (1)

Asperi
Asperi

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

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)
        }
    }
}

Upvotes: 5

Related Questions