我希望文本字段允许用户只粘贴字母数字文本中的数字并显示相同的内容。我已经处理过键盘部分。我已经尝试了委托方法但它完全限制了文本,如果它包含任何字母表,这不是我的要求。 我已经完成了讨论,但找不到我想要的东西。请尽快!
答案 0 :(得分:1)
试试这个
制作宏
#define ACCEPTABLE_CHARECTERS @"0123456789."
并使用它
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField==textFieldAmount)
{
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
return YES;
}
答案 1 :(得分:0)
使用以下代码检查您的文本字段是否仅包含数字:
BOOL valid;
NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:myInputField.text];
valid = [yourTextFieldText isSupersetOfSet:inStringSet];
if (!valid)
{
// Not numeric
}
else
{
//valid number
}
答案 2 :(得分:0)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet * characterSet = [[NSCharacterSet characterSetWithCharactersInString:@“0123456789”] invertedSet];
NSString * filtered = [[string componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:@“”];
textField.text = filtered;
返回NO;
}