UILabel 默認情況下,單行文本、使用固定寬高、固定字體的時候,超出的文本會被省略號代替,但對于某些設(shè)計中,省略號是不需要的(設(shè)計合理性不在本文討論范圍內(nèi))。考慮的采取幾種方式:
默認情況

方式一:設(shè)置 lineBreakMode
self.label1.lineBreakMode = NSLineBreakByWordWrapping;

方式二:提前計算UILabel 可容納的字數(shù)
實現(xiàn)可行,但總覺得每次渲染都得重新計算,這有多麻煩
方式三:取巧,使用UITextView 代替UILabel:
UITextView 是文本域的顯示組件,默認情況不存在最后一個字的溢出問題(折到第2行了),但UITextView 本身比UIlabel 可響應(yīng)用戶的操作更多,所以需要做一些設(shè)置才能保障正常的事件響應(yīng)(尤其在Cell 里面的時候)
示例(僅貼出主要差異部分)
CGFloat labelHeight = 22;
CGFloat fontSize = 15;
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.maximumLineHeight = labelHeight;
paragraphStyle.minimumLineHeight = labelHeight;
paragraphStyle.lineSpacing = labelHeight/2.0f;
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
NSAttributedString *aString = [[NSAttributedString alloc] initWithString:@"測試文字1標題測試" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[UIColor whiteColor],NSBaselineOffsetAttributeName:[NSNumber numberWithFloat:labelHeight/2.0f],NSParagraphStyleAttributeName:paragraphStyle}];
self.demoTextView.userInteractionEnabled = NO;
[self.demoTextView resignFirstResponder];
self.demoTextView.contentInset = UIEdgeInsetsMake(0, -4, 0, 0);
self.demoTextView.attributedText = aString;
最終效果:

注意點:
1.使用NSAttributedString對文本設(shè)置相應(yīng)的樣式和行高、行距;
2.禁止userInteractionEnabled,防止UITextView的事件響應(yīng)(編輯、選擇);
3.resignFirstResponder,設(shè)為非第一響應(yīng)者,在cell中尤其重要,否則點擊文字無法觸發(fā)cell 的 didSelected 的事件;
4.相比UILabel,內(nèi)存占用多一些,尤其在大量cell中使用時。
懶也是一種生產(chǎn)力