2012-05-08 187 views
1

我有一個UITextField,我限制輸入超過2位數。現在,它工作正常,但當我點擊文本字段&選擇所有內容&然後鍵入它不允許我覆蓋現有的2位數字。限制輸入到UITextField的字符數

關於如何在這裏使用'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; 
} 

回答

3

試試這個:

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