dakamojo
dakamojo

Reputation: 1955

iOS: How to send key to UITextField?

I have implemented a custom keyboard view in an iOS application. I have several UITextFields that use this keyboard. Some of these UITextFields have delegates that override shouldChangeCharactersInRange. However if my keyboard just sets the text value in the text field, the shouldChangeCharactersInRange message is not sent. What I think I need is to actually do something like SendKey and send the key code to the UITextField.

Any suggestions?

Upvotes: 8

Views: 3065

Answers (2)

Dan Rosenstark
Dan Rosenstark

Reputation: 69757

As I note in my answer here, the UITextField conforms to the UITextInput protocol. So you call its methods:

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

Of interest: "" will perform a backspace and, of course, " " will do a space.

This should call the shouldChangeCharactersInRange method automatically. If not, you'd have to do that yourself.

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

Upvotes: 5

BHSPitMonkey
BHSPitMonkey

Reputation: 655

It sounds like the keyboard is responsible for sending the shouldChangeCharactersInRange message to the UITextField itself, rather than just setting its value. Have your keyboard compute the values of range and string, and call:

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

Upvotes: -1

Related Questions