iPhone/iPad:在仅用于整数的文本框中检查无效字符

iPhone/iPad:在仅用于整数的文本框中检查无效字符,iphone,objective-c,cocoa-touch,uikit,ipad,Iphone,Objective C,Cocoa Touch,Uikit,Ipad,我注意到iPhone操作系统在被要求挑选整数值时表现得非常出色。具体来说,如果您使用 NSString *stringName = @"6("; int number = [stringName intValue]; iPhone操作系统将选择6,并将变量数字转换为6。但是,在更复杂的错误类型中,这也使得int变量6: NSString *stringName = @"6(5"; int number = [stringName intValue]; iPhone操作系统漏掉了另一个数字,当

我注意到iPhone操作系统在被要求挑选整数值时表现得非常出色。具体来说,如果您使用

NSString *stringName = @"6(";
int number = [stringName intValue];
iPhone操作系统将选择6,并将变量数字转换为6。但是,在更复杂的错误类型中,这也使得int变量6:

NSString *stringName = @"6(5";
int number = [stringName intValue];
iPhone操作系统漏掉了另一个数字,当可能是用户试图输入数字65时,操作系统只能从中得到数字6。我需要一个解决方案来检查字符串中的无效字符,如果文本框中除了无符号整数之外还有其他字符,则返回NO。这是为iPad设计的,目前没有像iPhone那样的数字键盘,取而代之的是标准的123键盘

我在想,我需要使用NSRange,以某种方式循环文本框中的整个字符串,并检查迭代中的当前字符是否为数字。我已经迷路了。我可以考虑用零来测试它,但是零是一个有效的整数


有人能帮忙吗?

我只想让
UITextField
的代表否决任何插入非数字字符的尝试。请参见
-textField:shouldChangeCharactersRange:replacementString:

我只想让
UITextField
的代理否决任何插入非数字字符的尝试。请参阅
-textField:shouldChangeCharactersRange:replacementString:

您可能想使用


使用NSScanner,您可以执行
-scanInt:
,然后选中
-isattend
,您可能需要使用


使用NSScanner,您可以执行
-scanit:
,然后检查
-isattend
实现NSResponder提到的
uitextfieldelegate
方法,并使用
NSString
方法
-rangeOfCharacterFromSet:
检查替换字符串,如下所示:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)newString
{
    // create a character set containing everything except the decimal digits
    // (you might want to cache this, as inverting the set probably isn't fast)
    NSCharacterSet *nonNumericCharacters = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    // and check whether there's a character in the string that's not in that set
    if([newString rangeOfCharacterFromSet:nonNumericCharacters].location != NSNotFound)
        return NO;
    return YES;
}

执行前面提到的
UITextFieldDelegate
方法NSResponder,并使用
NSString
方法
-rangeOfCharacterFromSet:
检查替换字符串,如下所示:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)newString
{
    // create a character set containing everything except the decimal digits
    // (you might want to cache this, as inverting the set probably isn't fast)
    NSCharacterSet *nonNumericCharacters = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    // and check whether there's a character in the string that's not in that set
    if([newString rangeOfCharacterFromSet:nonNumericCharacters].location != NSNotFound)
        return NO;
    return YES;
}
希望这有帮助

谢谢

马杜普

希望这有帮助

谢谢


Madhup

或者,更好的方法是告诉数字格式化程序尝试解析字符串。这将处理负数、小数点和区域设置更改(例如,不同的小数点)。当用户按backspace时,这可能会导致问题。或者,更好的是,告诉数字格式化程序尝试解析字符串。这将处理负数、小数点和区域设置更改(例如,不同的小数点)。当用户按backspace时,这可能会导致问题。零是一个有效的整数,但最近修订的苹果开发者协议也禁止它。与文本框一样:Pzero是一个有效的整数,但最近修订的苹果开发者协议也禁止使用它。与文本框一样:PI不认为有必要检查未输入的退格字符,您只会得到一个空字符串,替换插入符号前的任何字符。我认为没有必要检查未输入的退格字符,您只需要得到一个空字符串,它将替换插入符号前面的任何字符。