How do I force characters input into a textbox on the iPhone to upper case?
This solution is not fully satisfying.
Even with the autocapitalizationType set to UITextAutocapitalizationTypeAllCharacters, the user can still press caps to release the caps lock. And the textField.text = [textField.text stringByReplacingCharactersInRange:range withString:[string uppercaseString]]; return NO; solution is not that great: we loose the editing point if the user edits the middle of the text (after a textField.text =, the editing cursor goes to the end of the string).
I've done a mix of the two solution and here is what I propose: set UITextAutocapitalizationTypeAllCharacters, and add the following code to the delegate of the UITextField.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
// Check if the added string contains lowercase characters.
// If so, those characters are replaced by uppercase characters.
// But this has the effect of losing the editing point
// (only when trying to edit with lowercase characters),
// because the text of the UITextField is modified.
// That is why we only replace the text when this is really needed.
NSRange lowercaseCharRange;
lowercaseCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet lowercaseLetterCharacterSet]];
if (lowercaseCharRange.location != NSNotFound) {
textField.text = [textField.text stringByReplacingCharactersInRange:range
withString:[string uppercaseString]];
return NO;
}
return YES;
}