iOS只能输入数字与一个小数点,金额输入框。
//限制只能输入金额
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//首先设置:inputTF.keyboardType = UIKeyboardTypeDecimalPad;
NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
//限制.后面最多有两位,且不能再输入.
if ([textField.text rangeOfString:@"."].location != NSNotFound) {
//有.了 且.后面输入了两位 停止输入
if (toBeString.length > [toBeString rangeOfString:@"."].location+3) {
return NO;
}
//有.了,不允许再输入.
if ([string isEqualToString:@"."]) {
return NO;
}
}
//限制首位0,后面只能输入. 或 删除
if ([textField.text isEqualToString:@"0"]) {
if (!([string isEqualToString:@"."] || [string isEqualToString:@""])) {
return NO;
}
}
//首位. 前面补全0
if ([toBeString isEqualToString:@"."]) {
textField.text = @"0";
return YES;
}
//限制只能输入:1234567890.
NSCharacterSet * characterSet = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890."] invertedSet];
NSString * filtered = [[string componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
网友评论