第一個,來看下它的行間距
我用的是NSAttributeString
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:self.textView.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 5;
NSDictionary *attributes = @{
NSFontAttributeName :[UIFont systemFontOfSize:14],
NSParagraphStyleAttributeName:paragraphStyle
};
[attributedText addAttributes:attributes range:NSMakeRange(0, self.textView.text.length)];
self.textView.attributedText = attributedText;
NSMutableParagraphStyle是一個簡單富文本,替換文檔的固有屬性,可以在一定的字符范圍內變化。font、paragraph style、attachment(附件)。
第二個,滾動到最后一行
當文字比較多的時候,優先顯示最后一行
采用
[self.textView scrollRangeToVisible:NSMakeRange(self.textView.text.length, 1)];
或者:
CGRect caretRect = [self.textView caretRectForPosition:self.textView.endOfDocument];
[self.textView scrollRectToVisible:caretRect animated:NO];
感覺這個方法還是不太穩定,但是暫時沒有更好的解決方法了。
第三個,設計說要讓UITextView 左右兩邊留相同距離。
這個需求不可能實現這么精準,看圖。
做的時候才發現,UITextView不像UILabel那樣,他自己附加了一些展示的東西,上下左右預設了間距。所以我調了它的contentInset。
self.textView.contentInset = UIEdgeInsetsMake(10, -4, 0, -100);
變成下面這樣,
左間距,上間距有效,貌似右間距沒用。原本以為和contentSize有關,調了也沒用。這一點還不太清楚。
PS:上間距會根據文字內容多少和UITextView的高度來判斷是否取消。所以最好還是設contentInset的時候就把上間距搞掉。
第四個,類似文字自適應高度
最終我采用的
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 5;
NSDictionary *attributes = @{
NSFontAttributeName : Font(14),
NSParagraphStyleAttributeName : paragraphStyle
};
float stringHeight = [textView.text boundingRectWithSize:CGSizeMake(self.width - 24, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height;
這里想提下NSStringDrawingOptions:
enum { NSStringDrawingTruncatesLastVisibleLine = 1 << 5, NSStringDrawingUsesLineFragmentOrigin = 1 << 0, NSStringDrawingUsesFontLeading = 1 << 1, NSStringDrawingUsesDeviceMetrics = 1 << 3, }; typedef NSInteger NSStringDrawingOptions;
NSStringDrawingTruncatesLastVisibleLine:如果顯示不完全,會截斷,最后一行末尾顯示...。如果沒有指定NSStringDrawingUsesLineFragmentOrigin,這個選項會被忽略
NSStringDrawingUsesLineFragmentOrigin:繪制文本的時候指定的原點不是baseline origin,而是line fragement origin 。(這里不太清楚。。。)
NSStringDrawingUsesFontLeading:計算行高使用行間距(字體高+行間距=行高)
NSStringDrawingUsesDeviceMetrics:計算布局時使用圖元文字,而不是印刷字體。
一般用這兩個:
NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin
如果為
NSStringDrawingTruncatesLastVisibleLine或者NSStringDrawingUsesDeviceMetric,那么計算文本尺寸時將以每個字或字形為單位來計算。