iPhone Force Textbox Input to Upper Case

前端 未结 11 1634
无人共我
无人共我 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:20

    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;
    }
    

提交回复
热议问题