Ios UITextView根据行数和字符数限制文本
我有一个Ios UITextView根据行数和字符数限制文本,ios,uiview,uikit,uitextview,autolayout,Ios,Uiview,Uikit,Uitextview,Autolayout,我有一个UITextView, 我希望最多有两行 当文本视图达到两行且宽度结束时,我希望它停止接受任何新字符 我测试过: UITextView *textView = ... textView.textContainer.maximumNumberOfLines = 2; 这使文本视图的UI看起来正确,但它仍然接受新字符,并使文本增长到UI中可见的范围之外 仅仅限制字符数量并不是一个好主意,因为每个字符都有自己的宽度和高度 我正在使用自动布局。在文本视图的委托中,您可以使用textView:s
UITextView
,
我希望最多有两行
当文本视图达到两行且宽度结束时,我希望它停止接受任何新字符
我测试过:
UITextView *textView = ...
textView.textContainer.maximumNumberOfLines = 2;
这使文本视图的UI看起来正确,但它仍然接受新字符,并使文本增长到UI中可见的范围之外
仅仅限制字符数量并不是一个好主意,因为每个字符都有自己的宽度和高度
我正在使用自动布局。在文本视图的委托中,您可以使用
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;
}
-(BOOL)textView:(UITextView*)textView应更改textinrange:(nsrrange)范围替换text:(NSString*)文本
{
NSString*newText=[textView.text StringByReplacingCharactersRange:range with String: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)
选项:NSStringDrawingUserLineFragmentOrigin | NSStringDrawingUserFontLeading
属性:textAttributes
上下文:无];
nsuiger numberOfLines=CGRectGetHeight(boundingRect)/textView.font.lineHeight;
return newText.length基于文本是否应该受大小和字符数限制,还是只受大小限制的问题,有点不清楚。如果应该受大小限制,请删除newText.length只有您的答案对我有帮助!