触摸空格键时如何防止键盘从数字更改为字母?

Far*_*nen 5 iphone uitextfield iphone-sdk-3.0

UITextFields在桌子上输入值.其中一些字段仅接受数字.我UIKeyboardTypeNumbersAndPunctuation用于keyboardType,并shouldChangeCharactersInRange过滤字符.

此外,所有更正都被禁用:

textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
textField.autocorrectionType =  UITextAutocorrectionTypeNo;
textField.autocapitalizationType =  UITextAutocapitalizationTypeNone;
Run Code Online (Sandbox Code Playgroud)

在仅数字字段上,触摸空格键时,键盘将更改为字母.我知道这是默认行为.我想忽略空格键,不希望键盘类型改变.

有没有办法改变这种默认行为?

PS:其他数字键盘类型不是一个选项.我需要标点符号!

谢谢

ger*_*ry3 4

我认为不可能修改键盘行为。

但是,您可以从 UITextFieldDelegate 协议实现textField:shouldChangeCharactersInRange:replacementString:来拦截空格(和撇号),如下所示,它似乎有效:

- (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;
    }
}
Run Code Online (Sandbox Code Playgroud)