我有一个UITextField,你只能在其中输入数字和句号“,” 这就是它的制作方式:
#define NUMBERS @"0123456789"
#define NUMBERSPERIOD @"0123456789,"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *cs;
NSString *filtered;
// Check for period
if ([textFieled.text rangeOfString:@","].location == NSNotFound) {
cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERSPERIOD] invertedSet];
filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
// Period is in use
cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
现在我想将“,”之后输入的数字限制为2.我不知道该怎么做?
答案 0 :(得分:0)
int positionOfPeriod = [filtered rangeOfString:@","].location;
filtered = [filtered substringToIndex: MIN(positionOfPeriod+3, [filtered length])];