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 do开发者_开发技巧esn'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;
}
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.
[textField reloadInputViews]
seems to do the trick...
resignFirstResponder/becomeFirstResponder & reloadInputViews have some caveats. See stackoverflow.com/questions/5958427/…. These change the keyboard back to its initial state. So if the user had toggled to one of the other keyboard layouts (numbers, punctuation, etc), that state will get lost. I've never found a good solution.
精彩评论