将文本字段输入限制为仅一个小数点 [英] Limiting text field entry to only one decimal point
问题描述
我创建了一个文本字段来输入金额.我希望用户只能输入一个小数点.我在-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
方法中实现了这一点.
I have created a text field to enter an amount of money. I want the user to be able to enter only one decimal point. I implemented that in the -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
method.
在通常情况下,它可以正常工作,但是如果按了退格键并删除了一个小数点,此后它仍假定已输入一个小数点,因此不再接受该小数点.
In the general case it works fine, but if backspace is pressed and the single decimal point is deleted, after that it still assumes that a decimal point has been entered, and so does not accept the decimal point again.
每当按退格键删除小数点时,我都需要重置decimalPointEntered
标志.该怎么做?
I need to reset the decimalPointEntered
flag whenever the decimal point is deleted by pressing backspace. How to do that ?
推荐答案
这对我来说很好.尝试以下代码:
This works fine for me. Try this code:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *sep = [newString componentsSeparatedByString:@"."];
if([sep count] >= 2)
{
NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
return !([sepStr length]>1);
}
return YES;
}
这篇关于将文本字段输入限制为仅一个小数点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!