UITextField autocapitalizationType UITextAutocapit

2019-04-27 00:40发布

You can set the autocapitalizationType property of a UITextField so all input is in upper case. I find that does work fine on the simulator (when actually tapping the simulator's keypad, not the Mac's keyboard), but not on the device? Everything stays lowercase.

In the UICatalog demo I added to the textFieldNormal method:

textFieldNormal.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;

Added a delegate too, to display the actual autocapitalizationType for the UITextField:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog( @"textField.autocapitalizationType=%d", textField.autocapitalizationType );
}

It will properly display 3 (=UITextAutocapitalizationTypeAllCharacters), but anything you tap remains lowercase. What am I missing?

2条回答
啃猪蹄的小仙女
2楼-- · 2019-04-27 01:24

You could try something like this the the textfield delegate:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (range.length == 0) { // not deleting , but adding a char        
        textField.text = [textField.text stringByAppendingString:[string uppercaseString]];
        return NO;
    }

    return YES;
}

This works only if you try to insert a symbol at the end of the text. Should you want to play with the text in the middle you could play with

range.location

and also you will need to play with the cursor positioning as it will go at the end every time...

I hope this helps someone.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-04-27 01:27

Apparently this is a device general settings issue: Settings -> General -> Keyboard -> Auto-Capitalization must be ON to honour the setting of textField.autocapitalizationType to all upper case, else setting the property is ignored, apparently. If I switch it on everything works as expected.

查看更多
登录 后发表回答