user023
user023

Reputation: 1480

UITextView limit text due to number of lines and character count

I have a UITextView, which I would like to have two lines maximum.

When the text view has reached two lines and the end of its width, I want it to stop accepting any new characters.

I have tested:

UITextView *textView = ...
textView.textContainer.maximumNumberOfLines = 2;

This make the text view's UI look correctly but it still accepts new characters and grows the text beyond what is visible in the UI.

Just limiting the number of characters would not be a great idea since every character has its own width and height.

I'm using Auto Layout.

Upvotes: 2

Views: 2637

Answers (1)

Austin
Austin

Reputation: 5655

In the text view's delegate, you can use textView:shouldChangeTextInRange:replacementText: to return whether text entry should be accepted. Here's a snippet that calculates how tall the new text would be and returns true only if the text is less than the maximum characters allows and fits on two lines:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSString *newText = [textView.text stringByReplacingCharactersInRange:range withString:text];

    NSDictionary *textAttributes = @{NSFontAttributeName : textView.font};

    CGFloat textWidth = CGRectGetWidth(UIEdgeInsetsInsetRect(textView.frame, textView.textContainerInset));
    textWidth -= 2.0f * textView.textContainer.lineFragmentPadding;
    CGRect boundingRect = [newText boundingRectWithSize:CGSizeMake(textWidth, 0)
                                                options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                             attributes:textAttributes
                                                context:nil];

    NSUInteger numberOfLines = CGRectGetHeight(boundingRect) / textView.font.lineHeight;

    return newText.length <= 500 && numberOfLines <= 2;
}

Upvotes: 5

Related Questions