将UITextField限制为特定字符范围

时间:2012-05-01 11:00:33

标签: objective-c ios uitextfield uitextviewdelegate

有人可以帮我找出一种简单的方法来限制UITextField范围,这样输入的数字就在14到70之间,如果数字大于或小于范围内的数字,那么textfield就会自行清除?我已经将输入文本的长度限制为不超过2个字符,如下所示:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range      replacementString:(NSString *)string
{
NSString *newString = [ageField.text stringByReplacingCharactersInRange:range     withString:string];
return !([newString length] > 2);

唯一剩下的就是实现这种行为。任何人吗?

1 个答案:

答案 0 :(得分:1)

更新:

  NSInteger v = [newString integerValue];
 if (v < 14 || v > 72) {
// Do whatever you do when the string value is invalid
// BUT ALSO ADD:
textView.text = @"";
}

而不是返回尝试:

   if (newString.length != 2) {
  // do what you want!
return;
} else {
// PUT YOUR CODE HERE
}