由于行数和字符数,UITextView限制文本

use*_*023 2 uitextview uikit uiview ios autolayout

我有一个UITextView,我希望最多有两行.

当文本视图到达两行并且它的宽度结束时,我希望它停止接受任何新字符.

我测试过:

UITextView *textView = ...
textView.textContainer.maximumNumberOfLines = 2;
Run Code Online (Sandbox Code Playgroud)

这使得文本视图的UI看起来正确,但它仍然接受新字符,并使文本增长到UI中可见的范围之外.

仅限制字符数不是一个好主意,因为每个字符都有自己的宽度和高度.

我正在使用自动布局.

Aus*_*tin 5

在文本视图的委托中,您可以使用textView:shouldChangeTextInRange:replacementText:返回是否应接受文本输入.这是一个片段,用于计算新文本的高度,true仅当文本小于允许的最大字符数并且适合两行时返回:

- (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;
}
Run Code Online (Sandbox Code Playgroud)