Tuesday, 5 September 2023

Sure, here are the steps on how to detect keyboard show suggestion tapped in Swift code:

  1. Import the UITextField and NSNotificationCenter frameworks.

  2. Create a UITextField object and set its delegate property to an object that implements the UITextFieldDelegate protocol.

  3. In the UITextFieldDelegate protocol, implement the textFieldDidChange: method.

  4. In the textFieldDidChange: method, add an observer for the UIKeyboardWillShowNotification notification.

  5. In the UIKeyboardWillShowNotification notification handler, check if the keyboard is showing a suggestion bar.

  6. If the keyboard is showing a suggestion bar, check if the user tapped on a suggestion.

  7. If the user tapped on a suggestion, do something.

  8. Remove the observer for the UIKeyboardWillShowNotification notification.

Here is an example of how to implement this in Swift:

Swift

import UIKit

import NSNotificationCenter


class ViewController: UIViewController, UITextFieldDelegate {


    @IBOutlet weak var otpTextField: UITextField!


    override func viewDidLoad() {

        super.viewDidLoad()


        // Set the delegate property to an object that implements the UITextFieldDelegate protocol.

        otpTextField.delegate = self

    }


    func textFieldDidChange(_ textField: UITextField) {

        // Add an observer for the UIKeyboardWillShowNotification notification.

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)

   }


    @objc func keyboardWillShow(_ notification: NSNotification) {

        // Check if the keyboard is showing a suggestion bar.

        let keyboardFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect

        let suggestionBarFrame = notification.userInfo?[UIKeyboardSuggestionBarFrameEndUserInfoKey] as? CGRect


        if keyboardFrame != nil && suggestionBarFrame != nil {

            // The keyboard is showing a suggestion bar.

            // Check if the user tapped on a suggestion.

            if let tappedSuggestion = notification.userInfo?[UIKeyboardSuggestionBarSelectedSuggestionUserInfoKey] as? String {

                // The user tapped on a suggestion.

                // Do something.

            }

        }

    }


    func textFieldDidEndEditing(_ textField: UITextField) {

        // Remove the observer for the UIKeyboardWillShowNotification notification.

        NotificationCenter.default.removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)

    }

}


This code will detect if the user tapped on a suggestion in the keyboard suggestion bar and print a message to the console.

Sources

1. https://github.com/karthickkck315/Automatic-OTP