UIKeyboard turn Caps Lock on

与世无争的帅哥 提交于 2019-12-11 11:33:57

问题


I need my user to input some data like DF-DJSL so I put this in the code:

theTextField.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;

But unfortunately what happens is the first to letter type in CAPS but then letter immediately after typing the hyphen will be in lower case and then the rest return to CAPS therefore producing output like this (unless the user manually taps the shift button after typing a hyphen): DF-dJSL

How can I fix this?

Many Thanks


回答1:


You don't mention which SDK you're using, but against 3.0 and above I see your desired behaviour.

That said, you could always change the text to upper case when they finish editing using the textFieldDidEndEditing method from the delegate:

- (void)textFieldDidEndEditing:(UITextField *)textField {
    NSString *textToUpper = [textField.text uppercaseString];   
    [theTextField setText:textToUpper];
}

Or, by setting up a notification on the textfield when it changes, you could change the text as it is being typed:

// setup the UITextField
{
    theTextField.delegate = self;
    theTextField.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
    [theTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}

You have to do it this way since, unlike UISearchBar, UITextField doesn't implement textDidChange. Something like this, perhaps?

- (void)textFieldDidChange:(UITextField *)textField {
    NSRange range = [textField.text rangeOfString : @"-"];
    if (range.location != NSNotFound) {
        theTextField.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
    }
}


来源:https://stackoverflow.com/questions/2708775/uikeyboard-turn-caps-lock-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!