[UITextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
//方法实现
- (void)textFieldDidChange:(UITextField *)textField
{
//判断第一位是否为数字
if ([textField.text isEqualToString: @"."]) {
textField.text = @"";
}
//判断是否有两个小数点
if (textField.text.length >= 2) {
NSString *str = [textField.text substringToIndex:textField.text.length-1];
NSString *strTwo = [textField.text substringFromIndex:textField.text.length-1];
NSRange range = [str rangeOfString:@"."];
if (range.location != NSNotFound && [strTwo isEqualToString:@"."]) {
textField.text = [textField.text substringToIndex:textField.text.length-1];
}
}
//小数点后面数字位数控制 (此时为小数点后一位,3改4就是两位 思路:取倒数第X个字符是否为小数点,是小数点的话,就不再允许输入)
if (textField.text.length > 3) {
NSString *myStr = [textField.text substringWithRange:NSMakeRange(textField.text.length-3 , 1)];
if ([myStr isEqualToString:@"."]) {
textField.text = [textField.text substringToIndex:textField.text.length-1];
}
}
//最大值控制
double doubleNum = [textField.text doubleValue];
NSUInteger myNub = doubleNum;
NSUInteger sum = 100.0;
if (myNub > sum) {
textField.text = [textField.text substringToIndex:textField.text.length-1];
}
}
小白总结,欢迎打脸指正