我在優(yōu)化App的時(shí)候,看到價(jià)格不能隨意輸入,于是就在網(wǎng)上找了點(diǎn)案例。發(fā)現(xiàn)有一款方法非常好,能控制你的textfield,首字符不能輸入“0”或者“.”,控制小數(shù)點(diǎn)后面的分位數(shù)以及不讓小數(shù)點(diǎn)出現(xiàn)兩次。廢話不多說(shuō),直接粘貼demo。
圖.png
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([textField.text rangeOfString:@"."].location == NSNotFound)
{
isHaveDian = NO;
}
if ([string length] > 0)
{
unichar single = [string characterAtIndex:0];//當(dāng)前輸入的字符
if ((single >= '0' && single <= '9') || single == '.')//數(shù)據(jù)格式正確
{
//首字母不能為0和小數(shù)點(diǎn)
if([textField.text length] == 0)
{
if(single == '.')
{
[self showMyMessage:@"親,第一個(gè)數(shù)字不能為小數(shù)點(diǎn)!"];
[textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
if (single == '0')
{
[self showMyMessage:@"親,第一個(gè)數(shù)字不能為0!"];
[textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}
//輸入的字符是否是小數(shù)點(diǎn)
if (single == '.')
{
if(!isHaveDian)//text中還沒(méi)有小數(shù)點(diǎn)
{
isHaveDian = YES;
return YES;
}else{
[self showMyMessage:@"親,您已經(jīng)輸入過(guò)小數(shù)點(diǎn)了!"];
[textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}else{
if (isHaveDian) {//存在小數(shù)點(diǎn)
//判斷小數(shù)點(diǎn)的位數(shù)
NSRange ran = [textField.text rangeOfString:@"."];
if (range.location - ran.location <= 2) {
return YES;
}else{
[self showMyMessage:@"親,您最多輸入兩位小數(shù)!"];
return NO;
}
}else{
return YES;
}
}
}else{//輸入的數(shù)據(jù)格式不正確
[self showMyMessage:@"親,您輸入的格式不正確!"];
[textField.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}
else
{
return YES;
}
}
-(void)showMyMessage:(NSString*)aInfo {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:aInfo delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
[alertView show];
}
如果您覺(jué)得我的文章內(nèi)容對(duì)您有幫助,請(qǐng)點(diǎn)贊+關(guān)注。我會(huì)推薦出更多有用的文章。