UITextField 只能輸入數字、一個小數點、只能有兩位小數
//textField.text 輸入之前的值 string 輸入的字符
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
BOOL isHaveDian;
if ([textField1.text rangeOfString:@"."].location==NSNotFound) {
isHaveDian=NO;
}
if ([string length]>0)
{
unichar single=[string characterAtIndex:0];//當前輸入的字符
if ((single >='0' && single<='9') || single=='.')//數據格式正確
{
//首字母不能爲0和小數點
if([textField1.text length]==0){
if(single == '.'){
//[self alertView:@"親,第一個數字不能爲小數點"];
[textField1.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
if (single == '0') {
//[self alertView:@"親,第一個數字不能爲0"];
[textField1.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}
if (single=='.')
{
if(!isHaveDian)//text中還沒有小數點
{
isHaveDian=YES;
return YES;
}else
{
//[self alertView:@"親,您已經輸入過小數點了"];
[textField1.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}
else
{
if (isHaveDian)//存在小數點
{
//判斷小數點的位數
NSRange ran=[textField1.text rangeOfString:@"."];
int tt=range.location-ran.location;
if (tt <= 2){
return YES;
}else{
//[self alertView:@"親,您最多輸入兩位小數"];
return NO;
}
}
else
{
return YES;
}
}
}else{//輸入的數據格式不正確
[self alertView:@"親,您輸入的格式不正確"];
[textField1.text stringByReplacingCharactersInRange:range withString:@""];
return NO;
}
}
else
{
return YES;
}
}