限制输入到UITextField的字符数

时间:2012-05-08 23:08:31

标签: iphone objective-c ios cocoa-touch uitextfield

我有一个UITextField,我限制输入超过2位数。现在,它工作正常,但当我点击文本字段&选择所有内容&然后键入它不允许我覆盖现有的2位数。

有关如何使用' selectedTextRange'的任何线索这里的财产?

- (BOOL)cell:(RunnerTableViewCell *)iCell shouldChangeCharactersInRange:(NSRange)iRange replacementString:(NSString *)iString {
    self.navigationItem.rightBarButtonItem.enabled = YES;
    NSCharacterSet *anUnacceptedInput = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    int aCharacterUpperLimit = 2;
    BOOL aReturnValue = YES;

    NSInteger aTotalLength = iCell.inputField.text.length + [iString length];
    NSLog(@"iString=%@ aTotalLength=%d",iString,aTotalLength);
    if ([[iString componentsSeparatedByCharactersInSet:anUnacceptedInput] count] > 1 || (aTotalLength > aCharacterUpperLimit && ![iString isEqualToString:kRunnerEmptyString]) || [iString length] > aCharacterUpperLimit) {
        aReturnValue = NO;
    }
    return aReturnValue;
}

1 个答案:

答案 0 :(得分:3)

试试这个:

NSInteger aTotalLength = iCell.inputField.text.length + [iString length] - iRange.length;