1. 程式人生 > >iOS UITextView 內容顯示不全

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實際並不會滾動,並正確顯示出來內容