Asim Iftikhar Abbasi
Asim Iftikhar Abbasi

Reputation: 617

How to detect whether a hosting app's or custom keyboard text field is tapped in an iOS keyboard extension?

I am working on an iOS keyboard extension where I have a custom UITextField embedded within the keyboard itself. I need to differentiate between taps on my custom keyboard's text field and the hosting app's text field.

I currently have a flag, isSearchTextfieldTapped, to detect if the user has tapped on the keyboard's text field. This works fine in most cases. However, if the hosting app's text field is empty and the user taps on my keyboard's text field first, the flag becomes true as expected.

The issue arises when the user subsequently taps on the hosting app's text field. At this point, I need to reset the isSearchTextfieldTapped flag to false, but I can't figure out how to detect that the hosting app's text field has been selected after the keyboard's text field was tapped.

How can I detect when the user switches focus back to the hosting app's text field so I can reset my flag?

Here’s a simplified version of what I’ve tried:

    var isKeyboardTextFieldActive = false
    var isSearchTextfieldTapped = false

    override func textDidChange(_ textInput: UITextInput?) {
    print(#function)
    
    // The app has just changed the document's contents, the document context has been updated.
    if let beforeInput = proxy.documentContextBeforeInput {
        
        if beforeInput == searchTextfield.text {
            isKeyboardTextFieldActive = true
        } else {
            isKeyboardTextFieldActive = false
        }
        
    } else {
        if isSearchTextfieldTapped {
            isKeyboardTextFieldActive = true
        } else {
            isKeyboardTextFieldActive = false
        }
    }
}


 extension KeyboardViewController: UITextFieldDelegate{
    func textFieldDidBeginEditing(_ textField: UITextField) {
        isSearchTextfieldTapped = true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        isSearchTextfieldTapped = false
    }
}

Upvotes: 0

Views: 38

Answers (0)

Related Questions