直接在代理方法中写代码
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == yourTextField) {
NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
if ([toBeString containsString:@"."]) {
NSRange subRange = [toBeString rangeOfString:@"."];
if (toBeString.length - subRange.location > 3) { //如果输入框小数点后大于2位小数
textField.text = [toBeString substringToIndex:toBeString.length - 1];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"最多保留2位小数哦!" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
[alert show];
return NO;
}
}
}
return YES;
}