前言
YYKit作為業內的巔峰之作,其優異的性能和性能優化思路,都讓人嘆服。我也不禁一次地感嘆郭曜源憑借一人之力,寫出這樣的作品,真的是實至名歸的大神。但是老天總是愛開玩笑,16年大神得了一場罕見的病,17年博客留下最后一篇文章之后,就再也沒有出現在大家的視野中,我也一直想知道大神的近況,不為別的,只是想知道他身體還好,就感覺到很欣慰,這種感情就像是對一個老朋友,雖然我們素未謀面。
大神淡出大家視野之后,YYKit就停止了維護。期間,我斷斷續續的閱讀YYKit的相關源碼,也時常GitHub上看看相關的Issues,關注一下YYKit還有哪些需要改進的地方。其中在YYLabel中有一點,設置NSLineBreakByTruncatingHead
和NSLineBreakByTruncatingMiddle
,或者設置YYTextTruncationTypeStart
和YYTextTruncationTypeMiddle
后,效果和UILabel的不一樣。趁著現在不忙,和大家分享一下這個問題我認為可行的修復思路。
YYLabel正確設置截斷的方式實驗
首先,現有版本的YYLabel設置LineBreakMode,需要一點正確的姿勢,否則會發生一些問題。其中某些設置方式和代碼的順序也有關系,這是由于內部代碼實現邏輯的調用順序導致的。下邊是我用到的幾種設置LineBreakMode方法,主要是通過三個方面:
- 直接在YYLabel上設置
lineBreakMode
- 在YYTextContainer上設置
truncationToken
和truncationType
- 在NSAttributedString上設置
lineBreakMode
設置代碼如下:
NSString *str = @"你給過我太多的快樂和感動,太多的收獲和意外,也有太多的心酸和坎坷。可總歸你來過我的生命,也帶給我許多的美好和小幸福。我不知道是怎樣的緣分讓我們相遇,可我都不想去追究了,因為我相信每一種遇見,都有意義,每一個愛過的人,都有記憶。無論怎樣,都是幸運的,因為你帶給了我一些特殊的感受,以至于每次回味起來,都覺得人生是精彩的。";
NSMutableAttributedString *attText = [[NSMutableAttributedString alloc] initWithString:str];
// -- YY截斷限制1 - 直接在Label上設置
{
YYLabel *sourceLabel0 = [YYLabel new];
sourceLabel0.lineBreakMode = NSLineBreakByTruncatingMiddle;
sourceLabel0.numberOfLines = 3;//3
sourceLabel0.font = [UIFont systemFontOfSize:12];
sourceLabel0.frame = CGRectMake(20, 100, 320, 60);
sourceLabel0.text = str;
sourceLabel0.backgroundColor = [UIColor cyanColor];
[self.view addSubview:sourceLabel0];
}
// -- YY截斷限制1.1 - 直接在Label上設置
{
YYLabel *sourceLabel1 = [YYLabel new];
sourceLabel1.lineBreakMode = NSLineBreakByTruncatingMiddle;
sourceLabel1.numberOfLines = 0;//0
sourceLabel1.font = [UIFont systemFontOfSize:12];
sourceLabel1.frame = CGRectMake(20, 170, 320, 60);
sourceLabel1.text = str;
sourceLabel1.backgroundColor = [UIColor cyanColor];
[self.view addSubview:sourceLabel1];
}
// -- YY截斷限制2 - 直接在container上設置
{
YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(320, 60)];
container.maximumNumberOfRows = 3;
container.truncationType = YYTextTruncationTypeMiddle;
YYTextLayout * cardTextLayout = [YYTextLayout layoutWithContainer:container text:attText];
YYLabel *sourceLabel2 = [YYLabel new];
sourceLabel2.font = [UIFont systemFontOfSize:12];
sourceLabel2.frame = CGRectMake(20, 240, 320, 60);
sourceLabel2.textLayout = cardTextLayout;
sourceLabel2.backgroundColor = [UIColor cyanColor];
[self.view addSubview:sourceLabel2];
LxDBAnyVar(cardTextLayout.needDrawUnderline);
}
// -- YY截斷限制3 - 在富文本上設置lineBreakMode
{
NSString *str1 = @"你給過我太多的快樂和感動,太多的收獲和意外,也有太多的心酸和坎坷。可總歸你來過我的生命,也帶給我許多的美好和小幸福。我不知道是怎樣的緣分讓我們相遇,可我都不想去追究了,因為我相信每一種遇見,都有意義,每一個愛過的人,都有記憶。無論怎樣,都是幸運的,因為你帶給了我一些特殊的感受,以至于每次回味起來,都覺得人生是精彩的。";
NSMutableAttributedString *attText1 = [[NSMutableAttributedString alloc] initWithString:str1];
// attText可以添加 '\n', 有不同效果
attText1.minimumLineHeight = 50;
attText1.maximumLineHeight = 50;
attText1.lineBreakMode = NSLineBreakByTruncatingMiddle;
YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(320, 60)];
YYTextLayout * cardTextLayout = [YYTextLayout layoutWithContainer:container text:attText1];
YYLabel *sourceLabel3 = [YYLabel new];
sourceLabel3.font = [UIFont systemFontOfSize:12];
sourceLabel3.frame = CGRectMake(20, 310, 320, 60);
sourceLabel3.textLayout = cardTextLayout;
sourceLabel3.backgroundColor = [UIColor cyanColor];
[self.view addSubview:sourceLabel3];
}
// -- YY截斷限制3 - 給label設置textLayout
{
// container
YYTextContainer *container = [[YYTextContainer alloc] init];
container.size = CGSizeMake(300, 300); //設置height=1, 需要調整下邊代碼順序, `yysLabel.textLayout = xx` 會改變container.size
// textLayout
YYTextLayout *textLayout = [YYTextLayout layoutWithContainer:container text:attText];
// yysLabel
YYLabel *yysLabel = [YYLabel new];
yysLabel.backgroundColor = [UIColor cyanColor];
yysLabel.font = [UIFont systemFontOfSize:12];
yysLabel.frame= CGRectMake(20,380,320, 60);
yysLabel.textLayout = textLayout; // MARK:(如果container.size.height足夠大,那么textlayout和frame的設置順序無所謂。如果container.size.height小,比如=1,那么必須textlayout在設置frame上邊)
yysLabel.numberOfLines = 3;
yysLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
[self.view addSubview:yysLabel];
}
{
// container
YYTextContainer *container = [[YYTextContainer alloc] init];
container.size = CGSizeMake(300, 1);
// textLayout
YYTextLayout *textLayout = [YYTextLayout layoutWithContainer:container text:attText];
// yysLabel
YYLabel *yysLabel = [YYLabel new];
yysLabel.font = [UIFont systemFontOfSize:12];
yysLabel.backgroundColor = [UIColor cyanColor];
yysLabel.textLayout = textLayout; // MARK:(textlayout和frame不能顛倒順序,textlayout在上)
yysLabel.frame= CGRectMake(20,450,320, 60);
yysLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
[self.view addSubview:yysLabel];
}
//----------- UILabel
{
UILabel *uilabel = [UILabel new];
uilabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
uilabel.numberOfLines = 3;
uilabel.font = [UIFont systemFontOfSize:12];
uilabel.frame = CGRectMake(20, 530, 320, 60);
uilabel.text = str;
uilabel.backgroundColor = [UIColor orangeColor];
[self.view addSubview:uilabel];
}
{
UILabel *uilabel = [UILabel new];
uilabel.lineBreakMode = NSLineBreakByTruncatingHead;
uilabel.font = [UIFont systemFontOfSize:12];
uilabel.numberOfLines = 0; // 1, default
uilabel.frame = CGRectMake(20, 600, 320, 60);
uilabel.text = str;
uilabel.backgroundColor = [UIColor orangeColor];
[self.view addSubview:uilabel];
}
{
UILabel *uilabel = [UILabel new];
uilabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
uilabel.font = [UIFont systemFontOfSize:12];
uilabel.numberOfLines = 0; // 1, default
uilabel.frame = CGRectMake(20, 670, 320, 60);
uilabel.text = str;
uilabel.backgroundColor = [UIColor orangeColor];
[self.view addSubview:uilabel];
}
下面運行結果中橘色的部分是系統原生UIlabel設置LineBreak模式以后的效果,后續YYLabel修正結果便以此為參照標準。
從效果圖上我們可以看到,在不設置truncationToken
的前提下,YYLabel在設置Head
和Middle
之后,是在第n行(不是最后一行)的基礎上,行前或者行中加上省略號,然后行尾仍然有省略號。 如果直接在NSAttributedString上設置LineBreakMode
的話,最終效果是文本只會顯示一行。關于這一點,LineBreakMode
最后是設置到富文本的NSParagraphStyle
段落樣式的屬性中。當富文本中的NSParagraphStyle
屬性中的LineBreakMode
值有意義,那么用CTFramesetterRef
創建的CTLineRef
就只會有一行,所以是一行的顯示效果。
下邊是上邊示例中的NSParagraphStyle
包含了LineBreakMode 5
:
你給過我太多的快樂和感動,太多的收獲和意外,也有太多的心酸和坎坷。可總歸你來過我的生命,也帶給我許多的美好和小幸福。我不知道是怎樣的緣分讓我們相遇,可我都不想去追究了,因為我相信每一種遇見,都有意義,每一個愛過的人,都有記憶。無論怎樣,都是幸運的,因為你帶給了我一些特殊的感受,以至于每次回味起來,都覺得人生是精彩的。{
NSFont = "<UICTFont: 0x10a7003a0> font-family: \".SFUI-Regular\"; font-weight: normal; font-style: normal; font-size: 12.00pt";
NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 5, Tabs (\n 28L,\n 56L,\n 84L,\n 112L,\n 140L,\n 168L,\n 196L,\n 224L,\n 252L,\n 280L,\n 308L,\n 336L\n), DefaultTabInterval 0, Blocks [\n\n], Lists [\n\n], BaseWritingDirection -1, HyphenationFactor 0, TighteningForTruncation NO, HeaderLevel 0 LineBreakStrategy 0";
}
再看系統UILabel的效果,是取文本的最后一行,作為Head和Middle的最后一行。具體可以看上邊效果圖。
解決思路
YYText
中關于LineBreakMode
的核心計算代碼是在YYTextLayout
里的
+ (YYTextLayout *)layoutWithContainer:(YYTextContainer *)container text:(NSAttributedString *)text range:(NSRange)range
方法中,其中needTruncation
屬性是表示是否需要進行截斷相關操作。 主要思路是
- 第一步:判斷
用于繪制的lines數組的數量
是否超過maximumNumberOfRows
或者根據判斷當前CGPath
創建的CTFrameRef
中的用于繪制的lines數組的最后一行
是否小于傳入文本的字符長度,來確定needTruncation=YES
。- 第二步:如果
needTruncation=YES
,創建新的截斷line,并且賦值給truncatedLine
。- 第三步:在
YYTextDrawText(xxx)
方法中繪制CTRun的時候,發現繪制行是截斷行,則替換用truncatedLine
進行繪制。
其中第二步中,有這樣一行代碼
CTLineTruncationType type = kCTLineTruncationEnd;
if (container.truncationType == YYTextTruncationTypeStart) {
type = kCTLineTruncationStart;
} else if (container.truncationType == YYTextTruncationTypeMiddle) {
type = kCTLineTruncationMiddle;
}
NSMutableAttributedString *lastLineText = [text attributedSubstringFromRange:lastLine.range].mutableCopy;
// 對,就是下邊這一行
[lastLineText appendAttributedString:truncationToken];
CTLineRef ctLastLineExtend = CTLineCreateWithAttributedString((CFAttributedStringRef)lastLineText);
//......
CTLineRef ctTruncatedLine = CTLineCreateTruncatedLine(ctLastLineExtend, truncatedWidth, type, truncationTokenLine);
CFRelease(ctLastLineExtend);
truncationToken
是代表省略號富文本,YYLabel會根據最后一行line的富文本屬性,設置省略號的富文本屬性,然后將省略號拼接到lastLineText
后面。 最后,使用CTLineCreateTruncatedLine
方法來傳入對應的CTLineTruncationType
來創建截斷行。 其中,不管我們設置的CTLineTruncationType
是什么類型,truncationToken
都會拼接到lastLineText
后面,這就是導致YYLabel設置Head
和Middle
之后,一直會多一個省略號的原因。
解決該問題的思路就是,修正lastLineText
。替換[lastLineText appendAttributedString:truncationToken];
,新代碼很簡單:
NSMutableAttributedString *lastLineText = [text attributedSubstringFromRange:lastLine.range].mutableCopy;
if (type == kCTLineTruncationStart) {
NSMutableAttributedString *newLastLineText = [text attributedSubstringFromRange:(NSRange){text.length-lastLine.range.length, lastLine.range.length}].mutableCopy;
[newLastLineText replaceCharactersInRange:NSMakeRange(0, 1) withAttributedString:truncationToken];
lastLineText = newLastLineText;
}
else if (type == kCTLineTruncationMiddle) {
NSUInteger lastLineTextCount = lastLine.range.length;
NSUInteger lastLineTextMiddleIndex = lastLineTextCount/2;
NSMutableAttributedString *mutableTruncationToken = truncationToken.mutableCopy;
NSAttributedString *newLastLineEndText = [text attributedSubstringFromRange:(NSRange){text.length-lastLineTextMiddleIndex, lastLineTextMiddleIndex}];
[mutableTruncationToken appendAttributedString:newLastLineEndText];
[lastLineText replaceCharactersInRange:NSMakeRange(lastLineTextCount-mutableTruncationToken.length, mutableTruncationToken.length)
withAttributedString:mutableTruncationToken];
}
else {
[lastLineText appendAttributedString:truncationToken];
}
我在這里只是簡單的順著這個可行的思路進行了實驗,以默認的\u2026
為準,暫不支持自定義設置truncationToken
。當然你可以設置truncationToken
看看效果,大概率會導致最后一行Range計算不準確。關于truncationToken
,你可以自己修復一下。
結尾
截斷功能
只是YYLabel的一小方面,更是整個YYKit框架的冰山一角。再次感嘆郭曜源的對系統API的熟悉程度和各方面的優化思路。希望他能早日恢復健康,重回大家的視野。
交流
希望能和大家交流技術
Blog:http://www.lilongcnc.cc