How to prevent keyboard changing from Numbers to Alphabet when the space key is touched?

二次信任 提交于 2020-01-02 04:52:08

问题


I have UITextFields on a table to enter values. Some of these fields accept only numbers. I am using UIKeyboardTypeNumbersAndPunctuation for the keyboardType, and shouldChangeCharactersInRange to filter the characters.

Also, all the corrections are disabled:

textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
textField.autocorrectionType =  UITextAutocorrectionTypeNo;
textField.autocapitalizationType =  UITextAutocapitalizationTypeNone;

On the numeric only fields, when the space key is touched, the keyboard changes to Alphabet. I know that this is the default behavior. I want to ignore the space key, and don't want the keyboard type change.

Is there some way to change this default behavior?

PS: the other numeric keyboard types are not an option. I need the Punctuation!

Thanks


回答1:


I do not think it is possible to modify the keyboard behavior.

However, you could implement the textField:shouldChangeCharactersInRange:replacementString: from the UITextFieldDelegate protocol to intercept the space (and apostrophe) like this and it seems to work:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@" "] || [string isEqualToString:@"'"]) {
        NSMutableString *updatedString = [NSMutableString stringWithString:textField.text];
        [updatedString insertString:string atIndex:range.location];
        textField.text = updatedString;
        return NO;
    } else {
        return YES;
    }
}


来源:https://stackoverflow.com/questions/2071561/how-to-prevent-keyboard-changing-from-numbers-to-alphabet-when-the-space-key-is

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