输入框最多小数点后输入两位

输入控制:

/**

*  textFiled输入变化的时候

*

*  @param textField

replacementString //键盘每次输入的键

*/

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{

//控制输入个数

if (textField.tag == numberTextFieldTag) {

//判断是否为删除字符,如果为删除则让执行

if (string.length == 0) {

return YES;

}

//获取输入框内字符串

NSString *text = textField.text;

//判断是否有小数点

if ([text rangeOfString:@"."].length) {

//获取小数点后面字符串长度

if ([text substringFromIndex:[text rangeOfString:@"."].location].length > 2) {

return NO;

}else{

return YES;

}

}else{

return YES;

}

}

return YES;

}

提交时:

NSString *text = self.redPacketNumberTextField.text;

//判断输入是否合规

//如果存在"."

if ([text rangeOfString:@"."].location != NSNotFound) {

if ([text hasPrefix:@"."] || [text hasSuffix:@"."]) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:AppLocalizedString(@"Red Packet Amount error") delegate:self cancelButtonTitle:AppLocalizedString(@"OK") otherButtonTitles:nil, nil];

[alert show];

[self.redPacketNumberTextField becomeFirstResponder];

return;

}else{

//如果出现多个"."

NSString *str = [text substringFromIndex:[text rangeOfString:@"."].location + 1];

if ([str rangeOfString:@"."].location != NSNotFound) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:AppLocalizedString(@"Red Packet Amount error") delegate:self cancelButtonTitle:AppLocalizedString(@"OK") otherButtonTitles:nil, nil];

[alert show];

[self.redPacketNumberTextField becomeFirstResponder];

return;

}

//如果0开头,且小数点前面不止一位

if ([text hasPrefix:@"0"]){

NSString *perfixStr = [text substringWithRange:NSMakeRange(1, 1)];

if (![perfixStr isEqualToString:@"."]) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:AppLocalizedString(@"Red Packet Amount error") delegate:self cancelButtonTitle:AppLocalizedString(@"OK") otherButtonTitles:nil, nil];

[alert show];

[self.redPacketNumberTextField becomeFirstResponder];

return;

}

}

}

}else{

//如果没有小数点

//如果0开头

if ([text hasPrefix:@"0"]){

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:AppLocalizedString(@"Red Packet Amount error") delegate:self cancelButtonTitle:AppLocalizedString(@"OK") otherButtonTitles:nil, nil];

[alert show];

[self.redPacketNumberTextField becomeFirstResponder];

return;

}

}

你可能感兴趣的:(输入框最多小数点后输入两位)