如何限制UITextField中的小数点数? [英] How can I limit the number of decimal points in a UITextField?
本文介绍了如何限制UITextField中的小数点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个UITextField,点击后会在左下角显示一个带小数点的数字键盘。我试图限制该字段,以便用户只能放置1个十进制标记
I have a UITextField that when clicked brings up a number pad with a decimal point in the bottom left. I am trying to limit the field so that a user can only place 1 decimal mark
例如
2.5 OK
2 ..5不行
e.g.
2.5 OK
2..5 NOT OK
推荐答案
实现这样的shouldChangeCharactersInRange方法:
Implement the shouldChangeCharactersInRange method like this:
// Only allow one decimal point
// Example assumes ARC - Implement proper memory management if not using.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *arrayOfString = [newString componentsSeparatedByString:@"."];
if ([arrayOfString count] > 2 )
return NO;
return YES;
}
这会创建一个由小数点分割的字符串数组,所以如果有的话一个以上的小数点,我们将在数组中至少有3个元素。
This creates an array of strings split by the decimal point, so if there is more than one decimal point we will have at least 3 elements in the array.
这篇关于如何限制UITextField中的小数点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文