Search code examples
ioseventsxamarinxamarin.ioskeyboard

How to detect keyboard input in iOS?


I have a custom View and I need it to detect text input, like if it was a UITextField.

I have seen other questions where people suggest using an "invisible" UITextField to process the input, but this isn't valid for my View, since it's a drawing canvas with at Text Tool that allows the user to enter text.

Obviously, having a TextField as helper is really tricky and may interfere with the drawing routine.


Solution

  • I found out the answer: basically, you have to follow these steps:

    1. Add the [Adopts("UIKeyInput")] attribute to you view (adorning the class)
    2. Make your view implement the UIKeyInput interface
    3. override its CanBecomeFirstResponder method to return true.
    4. You should Implement the InsertText method of the UIKeyInput interface
    5. You can implement the rest of the members of UIKeyInput with the default values (they are mostly enums) and for HasText, you may just return true.to catch the text being typed by the user.

    With this setup, you just have to call the BecomeFirstResponder method on your view whenever you want your it to start receiving input from the user.

    Note: when I talk about "view" I mean the "class" of your view :)