Search code examples
iosuitextfielduitextfielddelegate

How to handle Tab key press in iOS?


I have a UIViewController which has 3 three UITextFields - TF1, TF2 and TF3. When the app is running on iOS simulator and I press Tab key, the focus moves to the next text field as expected.


TF3 is special. When the user taps on TF3, the text field should not get focused but instead a new view must be shown on the screen. I have implemented the UITextFieldDelegate method textFieldShouldBeginEditing(_:) to fix this as follows-

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    if (textField == TF3) {
        // show new view
        return false
    }
    return true
}

This works as expected.


After the above code is added, whenever the Tab key is pressed, the new view is shown. This is because whenever the Tab key is pressed, textFieldShouldBeginEditing(_:) is called on all the text fields on the screen.

Consider that TF1 is the first responder at present.

If I press Tab key, it moves the focus to TF2 as expected. However, the new view is also shown because textFieldShouldBeginEditing(_:) is called on TF3.


Can anyone point out how to solve this issue?


Solution

  • if I understand you correctly,what you want is below:

    Plan A

    var isTF3Beginned = false // a property of current view controller as flag
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if (textField == TF3 && isTF3Beginned == true) {
            // show new view
            return false
        }
        isTF3Beginned = true
        return true
    }
    

    Plan B RxSwift

    TF3.rx
    .controlEvent(.editingDidBegin)
    .skip(1)
    .subscribe(onNext: { () in
        // show new view
    }).disposed(by: disposeBag)