YYLabel - LineBreakMode效果修復思路

前言

YYKit作為業內的巔峰之作,其優異的性能和性能優化思路,都讓人嘆服。我也不禁一次地感嘆郭曜源憑借一人之力,寫出這樣的作品,真的是實至名歸的大神。但是老天總是愛開玩笑,16年大神得了一場罕見的病,17年博客留下最后一篇文章之后,就再也沒有出現在大家的視野中,我也一直想知道大神的近況,不為別的,只是想知道他身體還好,就感覺到很欣慰,這種感情就像是對一個老朋友,雖然我們素未謀面。

大神淡出大家視野之后,YYKit就停止了維護。期間,我斷斷續續的閱讀YYKit的相關源碼,也時常GitHub上看看相關的Issues,關注一下YYKit還有哪些需要改進的地方。其中在YYLabel中有一點,設置NSLineBreakByTruncatingHeadNSLineBreakByTruncatingMiddle,或者設置YYTextTruncationTypeStartYYTextTruncationTypeMiddle后,效果和UILabel的不一樣。趁著現在不忙,和大家分享一下這個問題我認為可行的修復思路。

YYLabel正確設置截斷的方式實驗

首先,現有版本的YYLabel設置LineBreakMode,需要一點正確的姿勢,否則會發生一些問題。其中某些設置方式和代碼的順序也有關系,這是由于內部代碼實現邏輯的調用順序導致的。下邊是我用到的幾種設置LineBreakMode方法,主要是通過三個方面:

  • 直接在YYLabel上設置lineBreakMode
  • 在YYTextContainer上設置truncationTokentruncationType
  • 在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修正結果便以此為參照標準。

藍色YYLabel,橘色UILabel

從效果圖上我們可以看到,在不設置truncationToken的前提下,YYLabel在設置HeadMiddle之后,是在第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的效果,是取文本的最后一行,作為HeadMiddle的最后一行。具體可以看上邊效果圖。

解決思路

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設置HeadMiddle之后,一直會多一個省略號的原因。

解決該問題的思路就是,修正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


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,488評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,034評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,327評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,554評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,337評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,883評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,975評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,114評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,625評論 1 332
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,555評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,737評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,244評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,973評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,362評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,615評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,343評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,699評論 2 370