【问题标题】:UITextView limit text due to number of lines and character count由于行数和字符数,UITextView 限制文本
【发布时间】:2014-08-20 12:57:35
【问题描述】:

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

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

我已经测试过:

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

这使文本视图的 UI 看起来正确,但它仍然接受新字符,并且使文本超出 UI 中可见的范围。

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

我正在使用自动布局。

【问题讨论】:

    标签: ios uiview uikit uitextview autolayout


    【解决方案1】:

    在文本视图的委托中,您可以使用textView:shouldChangeTextInRange:replacementText: 返回是否应接受文本输入。这是一个 sn-p,它计算新文本的高度并仅在文本小于允许的最大字符数且适合两行时返回 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;
    }
    

    【讨论】:

    • 基于文本是否应受大小和字符数限制或仅受大小限制的问题有点不清楚。如果它应该受大小限制,请从 return 语句中删除 newText.length &lt;= 500 &amp;&amp;
    • 只有你的回答对我有帮助!
    猜你喜欢
    • 2011-01-30
    • 1970-01-01
    • 2011-07-10
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    相关资源
    最近更新 更多