How to know whether the SecureField is editing

Viewed 621

I'm using SecureField to build a login page. However, I notice there is no onEditingChanged, so we can't know whether it's become first responder or not. Is there any solution to monitor this event?

2 Answers

You can create a model class that holds the variable for secureText value (In your case it should be LoginModel or something like that). Then bind the value to secureField text and add didSet on the Published var in the model. Here is an example:

Model:

class SecureFieldModel: ObservableObject {
    @Published var secureText = "" {
        didSet {
            print(secureText)
        }
    }
}

View:

@ObservedObject var model = SecureFieldModel()
    
struct LoginView: View {
   var body: some View {
      SecureField("Type your text here", text: $model.secureText)
   }
}

I think you may misunderstand my question. If the textfield is just focus, no text yet, we can't get the event. – RayChen 3 hours ago

Mantas answer slightly modified. "firing" when the input text has content or it is active:

struct ContentView: View {
    
    @ObservedObject var model = SecureFieldModel()
    
    var body: some View {
        // No info when focus removed
        SecureField("Type your text here", text: $model.secureText)
            .onTapGesture { // when active
                self.model.textFieldActivated()
            }

        // Do something when focus removed
        SecureField("Type your text here", text: $model.secureText, onCommit: {print("Commited and focus removed")})
            .onTapGesture { // when active
                self.model.textFieldActivated()
            }
    }
}

class SecureFieldModel: ObservableObject {
    @Published var secureText = "" {
        didSet {
            // if text
            if secureText.count >= 1 {
                print(secureText)
            }
        }
    }
    
    func textFieldActivated() {
        if secureText.count >= 1 {
            print(secureText)
        } else {
            print("is active")
        }
    }
}
Related