iOS UITextView 内容显示不全

当我们因为一些需求将UITextView当成UILabel使用(为了使用UITextView自带的复制,粘贴,选择功能,自动识别电话,邮箱,链接等等),这时我们只需要禁用UITextView的几个属性就行了

textView.editable = NO;//不可编辑
textView.scrollEnabled = NO;//不可滚动

然后计算文字的大小并设置UITextView的frame,我这里是xib里面的textView,

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:notification.content];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
[paragraphStyle setLineSpacing:5];

NSRange range = NSMakeRange(0,notification.content.length);

[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0x333333] range:range];
[attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15.0] range:range];

self.textView.attributedText = nil;
self.textView.attributedText = attributedString;

CGSize size = [self.textView.attributedText boundingRectWithSize:CGSizeMake(ScreenWidth-2*16, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;

self.textViewH.constant = size.height;

通过这种方法在UILabel上使用没有任何问题,但是文本显示不全,或者有的计算出来的高度比文字的实际高度要大,所以还需要再设置一些属性:

[self.textView setContentInset:UIEdgeInsetsMake(-10, -5, -15, -5)];//设置UITextView的内边距
[self.textView setTextAlignment:NSTextAlignmentLeft];//并设置左对齐
self.textView.layoutManager.allowsNonContiguousLayout = NO;
self.textView.scrollEnabled = YES;  //  如果scrollEnabled=NO,计算出来的还是不正确的,这里虽然设置为YES,但textView实际并不会滚动,并正确显示出来内容

你可能感兴趣的:(Xcode-小知识点)