iPhone Force Textbox Input to Upper Case

前端 未结 11 1625
无人共我
无人共我 2020-12-15 03:01

How do I force characters input into a textbox on the iPhone to upper case?

11条回答
  •  攒了一身酷
    2020-12-15 03:31

    While all the other answers do actually work (they make the input uppercase), they all have the problem that the cursor position is not retained (try inserting a character in the middle of the existing text). This apparently happens in the setter of UITextField's text property, and I have not found a way to restore it programmatically (for example, restoring the original selectedTextRange does not work).

    However, the good news is, that there is a direct way to replace parts of a UITextField's (or UITextView's) text, which does not suffer from this issue:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        // not so easy to get an UITextRange from an NSRange...
        // thanks to Nicolas Bachschmidt (see http://stackoverflow.com/questions/9126709/create-uitextrange-from-nsrange)
        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];
    
        // replace the text in the range with the upper case version of the replacement string
        [textField replaceRange:textRange withText:[string uppercaseString]];
    
        // don't change the characters automatically
        return NO;
    }
    

    For further information on these methods, see the documentation of UITextInput.

提交回复
热议问题