views:

501

answers:

1

Hiya!

I want to change the UITextInputTraits of a keyboard while it is in use....

My ideal code would look something like this:

- (IBAction)nameTextDidChange:(UITextField *)sender {
    if ([sender.text isEqualToString:@""]) {
        sender.returnKeyType = UIReturnKeyDone;
    } else {
        sender.returnKeyType = UIReturnKeySearch;
    }
}

So... I have a different 'Return' button for an empty string as I do a string with some text in. The code I posted above doesn't work, the keyboard retains it's original text input traits.

Any ideas anyone, or is this never going to work no-matter how hard I try?

Cheers!

Nick.

Thanks to Deepak, this is the code I actually used:

if ([sender.text isEqualToString:@""]) {
    sender.returnKeyType = UIReturnKeyDone;

    [sender resignFirstResponder];
    [sender becomeFirstResponder];
} else if (sender.returnKeyType == UIReturnKeyDone) {

    NSString *cachedLetter = sender.text;

    sender.returnKeyType = UIReturnKeySearch;

    [sender resignFirstResponder];
    [sender becomeFirstResponder];

    sender.text = cachedLetter;
}
+1  A: 

You can make this work by adding the following lines at the end of the method.

if ([textField.text isEqualToString:@""]) {
    textField.returnKeyType = UIReturnKeyDone;

    [textField resignFirstResponder];
    [textField becomeFirstResponder];
} else if (textField.returnKeyType == UIReturnKeyDone) {
    textField.returnKeyType = UIReturnKeySearch;

    [textField resignFirstResponder];
    [textField becomeFirstResponder];
}

This should work.

You basically flip it on and off so that the text input changes. The second if is to make sure you flip only if needed.

Deepak
Genius, thanks so much for this. It worked almost perfectly.. the only thing that didn't work was when you resign a keyboard, you loose the text in the UITextField - so I just had to cache that! I'll post the exact code I used in my question for others.
Nick Cartwright