如何限制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.