問題描述
我有一個UITextField
,我想限制該字段中允許的最大輸入值為1000.那是當用戶在里面輸入數字時,一旦輸入值大于999,除非用戶輸入小于 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.
我想我應該使用 UITextField
委托來限制輸入:
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?
==========更新=============
我的輸入框不僅允許用戶輸入整數,還可以輸入浮點值,如 999,03
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 : 限制輸入時允許的最大值(數字)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!