JMD
JMD

Reputation: 1590

invoke textFieldShouldReturn with a custom keyboard

I have a custom keyboard, which is set up with a UITextInput delegate for sending in text to the current text field. But I need to also send a 'return' press to invoke the textFieldShouldReturn method and as far as I can tell, UITextInput does not allow this. (unless there is some kind of specific character for the return key?)

So how exactly do you pass a 'return' key press value to a text field to trigger the textFieldShouldReturn?

Upvotes: 1

Views: 1248

Answers (3)

AlleyGator
AlleyGator

Reputation: 1276

You're headed in the wrong direction here, because you're already using a custom keyboard. That should eliminate you from needing to use a UITextFieldDelegate to solve the problem of return key detection.

textFieldShouldReturn: is a delegate method of the UITextField used to detect when the user presses the return key. If you didn't have this method, you'd have to use textField:shouldChangeCharactersInRange:replacementString: to detect the newline character from a normal UIKeyboard, which would be a pain in the butt.

But if you have a particular button on your keyboard that should do something special, just wire that button up to your IBAction method directly.

So something like this:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
   [self returnKeyPressed:textField];
   return NO;
}

- (IBAction)returnKeyPressed:(id)sender {
   // Do whatever you want done
}

If you wire your custom key to returnKeyPressed:, both a hardware keyboard and your virtual custom keyboard would end up in returnKeyPressed: and the behavior would be consistent.

You probably would want to define a small protocol to make sure your delegates support returnKeyPressed: in addition to the UITextFieldDelegate methods.

Upvotes: 0

Albert Renshaw
Albert Renshaw

Reputation: 17882

The specific character for the return key is \n adding that to the end of your string will put your cursor on the next line...

*then to actually call the textFieldShouldReturn method, if you still want to do that for some reason, you just call it like you would any method.

Upvotes: 2

apascual
apascual

Reputation: 2980

You should implement this:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return NO;
}

Upvotes: 1

Related Questions