UITextField:在输入期间限制最大允许值(数字) [英] UITextField : restrict the maximum allowed value (number) during inputting

查看:951
本文介绍了UITextField:在输入期间限制最大允许值(数字)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UITextField ,我想限制在字段中的最大允许输入值为1000.这是当用户输入数字内,一旦输入值大于999,则输入字段中的值将不再更新,除非用户输入的值小于1000.



我想应该使用 UITextField 委托限制输入:

   - (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
//如何做
}

但我不知道如何实现它。有任何建议吗?



==========更新============= / p>

我的输入字段不仅允许用户输入整数,还可以输入如999,03的浮动值

解决方案

您应该在上述方法中执行以下操作:

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

//首先,检查新字符串是否只是数字。如果不是,返回NO;
NSCharacterSet * characterSet = [[NSCharacterSet characterSetWithCharactersInString:@0123456789 ,.] invertedSet];
if([newString rangeOfCharacterFromSet:characterSet] .location!= NSNotFound)
{
return NO;
}

return [newString doubleValue] 1000;


I have a UITextField, I'd like to restrict the maximum allowed input value in the field to be 1000. That's when user is inputting number inside, once the input value is larger than 999, the value in input field won't be updated anymore unless user is inputting value less than 1000.

I think I should use UITextField delegate to limit the input:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
  //How to do
}

But I am not sure how to implement it. Any suggestions?

==========Update=============

my input field not only allow user to input integer, but also float value like 999,03

解决方案

You should do the following inside the above method:

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

//first, check if the new string is numeric only. If not, return NO;
NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789,."] invertedSet];
if ([newString rangeOfCharacterFromSet:characterSet].location != NSNotFound)
{
    return NO;
}

return [newString doubleValue] < 1000;

这篇关于UITextField:在输入期间限制最大允许值(数字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆