IOS: How to send a key to a UITextField?

I implemented a custom keyboard look in an iOS app. I have several UITextFields that use this keyboard. Some of these UITextFields have delegates that override shouldChangeCharactersInRange . However, if my keyboard simply sets a text value to a text field, the shouldChangeCharactersInRange message is not sent. It seems to me that I need to do something like SendKey and send the key code to a UITextField.

Any suggestions?

+7
source share
2 answers

As I point out in my answer here , the UITextField conforms to the UITextInput protocol. Therefore, you call its methods:

 [textField replaceRange:textField.selectedTextRange withText:text]; 

Interesting: "" will do the backspace and, of course, " " will do the space.

This should call the shouldChangeCharactersInRange method automatically. If not, you must do it yourself.

You definitely need to do this if you are going to create a custom keyboard on iOS.

+5
source

It seems that the keyboard is responsible for sending the shouldChangeCharactersInRange message to the UITextField itself, and not just setting its value. Ask the keyboard to calculate the range and string values ​​and call:

 if ([[theTextField delegate] textField:theTextField shouldChangeCharactersInRange:range replacementString:string]) theTextField.text = [theTextField.text stringByReplacingCharactersInRange:range withString:string]; 
-one
source

All Articles