iOS 輸入金錢數目的TextField
GitHub地址:https://github.com/wukaiqiang/KQWithdrawTextFieldDemo
使用cocoapods匯入:pod 'KQWithdrawTextField'
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField.text.length > 10) {
return range.location < 11;
}else
BOOL isHaveDian = YES;
if ([textField.text rangeOfString:@"."].location==NSNotFound) {
isHaveDian=NO;
}
if ([string length]>0) {
unichar single=[string characterAtIndex:0];//當前輸入的字元
if ((single >='0' && single<='9') || single=='.') {//資料格式正確
//首字母不能為小數點
if
if(single == '.') {
[textField.text stringByReplacingCharactersInRange:range withString:@""];
returnNO;
}
}
if([textField.text length]==1 && [textField.text isEqualToString:@"0"]){
if(single != '.'){
[textField.text stringByReplacingCharactersInRange:range withString:
returnNO;
}
}
if (single=='.') {
if(!isHaveDian) {//text中還沒有小數點
isHaveDian=YES;
returnYES;
}else {
[textField.text stringByReplacingCharactersInRange:range withString:@""];
returnNO;
}
}else {
if (isHaveDian)//存在小數點
{
//判斷小數點的位數
NSRange ran=[textField.text rangeOfString:@"."];
NSInteger tt=range.location-ran.location;
if (tt <= 2){
returnYES;
}else{
returnNO;
}
}else {
returnYES;
}
}
}else{//輸入的資料格式不正確
[textField.text stringByReplacingCharactersInRange:range withString:@""];
returnNO;
}
}else {
returnYES;
}
}
}