文本验证 - 用户只能选择一次数字

时间:2011-04-20 12:56:23

标签: iphone objective-c xcode uitextfield

我正在尝试创建一份问卷,其中用户应对1-7的语句进行评分。

用户通过填充UITextFields并使用1-7之间的值来对语句进行评级。

我已经做到了这样,用户只能写入1-7之间的值,并且每个文本字段只能写一个字符。

我现在要做的是阻止用户多次使用该值。

这是我到目前为止的代码。

#define CHARACTERS          @"1234567"

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
// These are the characters that are ~not~ acceptable
NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:CHARACTERS] invertedSet];

 NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

if (([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] >1 ) | ([newString length] > 1) )
return NO;
else
return YES;
}

3 个答案:

答案 0 :(得分:1)

我会用字典。每当在文本字段中选择一个数字时,检查字典是否具有该值。如果没有该值,则输入的值是正确的。现在将条目添加到字典中,然后让用户进入下一个文本字段。如果您对所有文本字段重复此过程,您将能够非常轻松地解决此问题。

答案 1 :(得分:0)


您可以做一件事给所有文本字段添加标签,并检查您在当前文本字段中输入的字符串是否与所有其他文本字段的文本相同,然后返回NO。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
// These are the characters that are ~not~ acceptable
NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:CHARACTERS] invertedSet];

NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

if (([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] >1 ) | ([newString length] > 1) )
   return NO;
else
   //Call function to check if string is same as other textfield.text then return NO else YES
}

否则
另一个选项是你可以取1个字符串并在该字符串中保存textfield.text并在你输入时更新所有时间并检查你输入的字符串是否在该字符串的子字符串中。  祝你好运

答案 2 :(得分:-1)

在创建UITextField时,将keyboardType设置为UIKeyboardTypeNumberPad。

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{
    if([[textField text]length]==1)
    //perform condition

    else
    //perform condition
}

这可能会有所帮助