Last active
January 5, 2022 03:41
-
-
Save gleue/9806181 to your computer and use it in GitHub Desktop.
Force input into UITextField to uppercase
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string | |
{ | |
// Inspiration: http://stackoverflow.com/a/6265614 and http://stackoverflow.com/a/13388037 | |
// | |
// Check if the added string contains lowercase characters. | |
// If so, those characters are replaced by uppercase characters. | |
// | |
NSRange lowercaseCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet lowercaseLetterCharacterSet]]; | |
if (lowercaseCharRange.location != NSNotFound) { | |
if (textField.text.length == 0) { | |
// Add first character -- and update Return button | |
// | |
// 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, | |
// which does not matter since the caret is at the end | |
// of the (empty) text fiueld anyways. | |
// | |
textField.text = [textField.text stringByReplacingCharactersInRange:range withString:[string uppercaseString]]; | |
} else { | |
// Replace range instead of whole string in order | |
// not to lose input caret position -- but this will | |
// not update the Return button, which is not necessary | |
// here anyways | |
// | |
UITextPosition *beginning = textField.beginningOfDocument; | |
UITextPosition *start = [textField positionFromPosition:beginning offset:range.location]; | |
UITextPosition *end = [textField positionFromPosition:start offset:range.length]; | |
UITextRange *textRange = [textField textRangeFromPosition:start toPosition:end]; | |
[textField replaceRange:textRange withText:[string uppercaseString]]; | |
} | |
return NO; | |
} | |
return YES | |
} |
This is almost good, but the first character will always be small
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
SWIFT