1.簡述
最近忙著做一個賬單管理APP物延,在添加賬單的界面中,有一個輸入金額的UITextField昭雌。
要求:每筆賬單的收入或支出金額不超過9位數(shù)蜒蕾,小數(shù)點后保留兩位小數(shù)兰绣。
2.使用的方法
UITextFieldDelegate 中的
- (BOOL)textField:(UITextField*)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString*)string;
用戶每輸入一個字符就會調用該方法膘螟,點擊鍵盤的刪除按鈕也會調用虽惭。
參數(shù)解析:
2.1 textField
在該方法內敌蚜,我們可以使用
[textField isEqual:self.billAmountTextField];
來判斷用戶是否在相應的TextField中輸入字符候衍。
2.2 NSRange是一個結構體
它有兩個NSUInteger類型的屬性笼蛛,一個是length,一個是location
我們可以使用range.location來訪問用戶輸入的字符在整個textField.text字符串中的位置蛉鹿,
位置的編號從零開始滨砍,也就是說:
當用戶在UITextField中輸入第一個字符后,range.location的值為0,以此類推;
2.3 string
string就是用戶“一次”輸入的字符或者字符串,而不是當前UITextField中所包含的所有字符妖异,
它不會對多次輸入的字符進行拼接惋戏。
比如用戶第一次輸入了“我吃了”,第二次輸入了“晚飯”他膳。
那么string的內容分別是“我吃了”和“晚飯”响逢,而不是“我吃了”和“我吃了晚飯”。
3.代碼
#define NumbersWithDot @"0123456789.\n"
#define NumbersWithoutDot @"0123456789\n"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// 判斷是否輸入內容棕孙,或者用戶點擊的是鍵盤的刪除按鈕
if (![string isEqualToString:@""]) {
NSCharacterSet *cs;
if ([textField isEqual:self.billAmountTextField]) {
// 小數(shù)點在字符串中的位置 第一個數(shù)字從0位置開始
NSInteger dotLocation = [textField.text rangeOfString:@"."].location;
// 判斷字符串中是否有小數(shù)點舔亭,并且小數(shù)點不在第一位
// NSNotFound 表示請求操作的某個內容或者item沒有發(fā)現(xiàn),或者不存在
// range.location 表示的是當前輸入的內容在整個字符串中的位置蟀俊,位置編號從0開始
if (dotLocation == NSNotFound && range.location != 0) {
// 取只包含“myDotNumbers”中包含的內容分歇,其余內容都被去掉
/*
[NSCharacterSet characterSetWithCharactersInString:myDotNumbers]的作用是去掉"myDotNumbers"中包含的所有內容,只要字符串中有內容與"myDotNumbers"中的部分內容相同都會被舍去
在上述方法的末尾加上invertedSet就會使作用顛倒欧漱,只取與“myDotNumbers”中內容相同的字符
*/
cs = [[NSCharacterSet characterSetWithCharactersInString:NumbersWithDot] invertedSet];
if (range.location >= 9) {
NSLog(@"單筆金額不能超過億位");
if ([string isEqualToString:@"."] && range.location == 9) {
return YES;
}
return NO;
}
}else {
cs = [[NSCharacterSet characterSetWithCharactersInString:NumbersWithoutDot] invertedSet];
}
// 按cs分離出數(shù)組,數(shù)組按@""分離出字符串
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
BOOL basicTest = [string isEqualToString:filtered];
if (!basicTest) {
NSLog(@"只能輸入數(shù)字和小數(shù)點");
return NO;
}
if (dotLocation != NSNotFound && range.location > dotLocation + 2) {
NSLog(@"小數(shù)點后最多兩位");
return NO;
}
if (textField.text.length > 11) {
return NO;
}
}
}
return YES;
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者