UITextField限制句点后的数字“,”

时间:2012-06-27 22:40:25

标签: iphone xcode uitextfield

我有一个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.我不知道该怎么做?

1 个答案:

答案 0 :(得分:0)

int positionOfPeriod = [filtered rangeOfString:@","].location;
filtered = [filtered substringToIndex: MIN(positionOfPeriod+3, [filtered length])];