I am working on a form which contains multiple UITextField
instances, and I need to trigger a side effect (i.e. present an alert) when one particular text field, whose textFieldShouldBeginEditing(_:)
delegate method always returns false
, is selected.
The existing implementation of this feature triggered that side effect in the delegate's textFieldShouldBeginEditing(_:)
method. This was causing issues on iPad Pro because when the user presses the on-screen keyboard's Tab key that method is not just invoked for the next responder, but for all the text fields in the form, yielding the side effect to be triggered at inappropriate times.
Having read this related question, I tried registering my view controller for UIKeyCommands as in this simplified example, so as to explicitly handle Tab key presses:
override func viewDidLoad() {
super.viewDidLoad()
for textField in [textField1, textField2, textField3] {
textField?.delegate = self
}
let keyCommand = UIKeyCommand(input: "\t", modifierFlags: [], action: #selector(didPressTabKey(sender:)))
self.addKeyCommand(keyCommand)
}
@objc func didPressTabKey(sender: UIKeyCommand) {
NSLog("Did press tab key")
}
Unfortunately, the UIKeyCommand
's action is only invoked when the Tab key is pressed on an external keyboard (i.e. the Mac's keyboard when running on the Simulator), and it never fires when using the iPad Pro's on-screen keyboard (on Simulator and actual devices).
An obvious way to work around this issue is to move the side effect away from textFieldShouldBeginEditing(_:)
and into textFieldDidBeginEditing(_:)
, but given that I need to trigger it when textFieldShouldBeginEditing(_:)
returns false
, this approach is not satisfactory.
The current workaround I implemented is to remove the side effect from textFieldShouldBeginEditing(_:)
and explicitly listen for taps on the UITextField
. With this approach, the side effect is correctly triggered when the user selects that specific text field, but there is no way to trigger it when the user presses the Tab key while editing the previous field in the form's tab order.
Is there a way to intercept Tab key presses from the on-screen keyboard?