Detecting Key Press/ Key Down iOS

Viewed 51

I am developing a library, which will be used in an app, where I need to know the timestamp of key pressed (key down and key up moments), in the iOS(iPhone) virtual keyboard.

I was trying to do it by inheritance from UIViewController and override pressesBegan and pressesEnded functions like here, but it turns out its only working for external physical keyboards (so like >1% users of iPhones?)

I was trying to do this by getting all the textFields:

func getAllTextFields(fromView view: UIView)-> [UITextField] {
    return view.subviews.flatMap { (view) -> [UITextField] in
        if view is UITextField {
            return [(view as! UITextField)]
        } else {
            return getAllTextFields(fromView: view)
        }
    }.flatMap({$0})
}

and use of .addTarget method but there's no function which provide information about "key down" moment:

textFields.forEach{($0.addTarget(self, action: #selector(textFieldEditingBegin),
                                         for: .editingDidBegin))}

textFields.forEach{($0.addTarget(self, action: #selector(textFieldDidChange),
                                         for: .editingChanged))}

textFields.forEach{($0.addTarget(self, action: #selector(textFieldDidEnd),
                                         for: .editingDidEnd))}

The .editingChanged method can only be translated to "key up". The other ones, tells us about whole textField, so the moment when user "tap" on it and not the moment when he "tap" the letter in the virtual keyboard.

I have not found anything useful for me in the NotificationCenter, UIResponder or UITextFieldDelegate.

So im asking if anyone knows how can I retrieve such information from a iOS keyboard, im not very familiar with Extension mechanism and maybe there is some other stuff im able to do in my scenario.

Thanks.

1 Answers

You can detect user's tap using UITextFieldDelegate

func textFieldDidBeginEditing(_ textField: UITextField) // became first responder
Related