1. 程式人生 > >UITextView 限制字數

UITextView 限制字數

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

{

    if ([text rangeOfString:@"\n"].length > 0) {

        [textView resignFirstResponder];

        return NO;

    }

    int maxTextCount = 200;    

    NSString *string = nil;

    if (range.length > 0) {

        if ([textView.text length] >= range.location) {

            string = [textView.text substringToIndex:range.location];

        }

    

        string = [NSString stringWithFormat:@"%@%@", string, text];

        if ([textView.text length] > range.location + range.length) {

            string = [NSString stringWithFormat:@"%@%@", string, [textView.text substringFromIndex:range.location + range.length]];

        }

    } else {

        string = [NSString stringWithFormat:@"%@%@", textView.text, text];

    }

    

    if (string.length > maxTextCount) {

        NSRange rangeIndex = [string rangeOfComposedCharacterSequenceAtIndex:maxTextCount];

        if (rangeIndex.length == 1) {//字數超限

            textView.text = [string substringToIndex:maxTextCount];

        }else{

            NSRange rangeRange = [string rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxTextCount)];

            textView.text = [string substringWithRange:rangeRange];

        }

        

        return NO;

    }

 

    return YES;

}