iOS

YYLabel - LineBreakMode效果修复思路

2019-10-16  本文已影响0人  春田花花幼儿园

前言

YYKit作为业内的巅峰之作,其优异的性能和性能优化思路,都让人叹服。我也不禁一次地感叹郭曜源凭借一人之力,写出这样的作品,真的是实至名归的大神。但是老天总是爱开玩笑,16年大神得了一场罕见的病,17年博客留下最后一篇文章之后,就再也没有出现在大家的视野中,我也一直想知道大神的近况,不为别的,只是想知道他身体还好,就感觉到很欣慰,这种感情就像是对一个老朋友,虽然我们素未谋面。

大神淡出大家视野之后,YYKit就停止了维护。期间,我断断续续的阅读YYKit的相关源码,也时常GitHub上看看相关的Issues,关注一下YYKit还有哪些需要改进的地方。其中在YYLabel中有一点,设置NSLineBreakByTruncatingHeadNSLineBreakByTruncatingMiddle,或者设置YYTextTruncationTypeStartYYTextTruncationTypeMiddle后,效果和UILabel的不一样。趁着现在不忙,和大家分享一下这个问题我认为可行的修复思路。

YYLabel正确设置截断的方式实验

首先,现有版本的YYLabel设置LineBreakMode,需要一点正确的姿势,否则会发生一些问题。其中某些设置方式和代码的顺序也有关系,这是由于内部代码实现逻辑的调用顺序导致的。下边是我用到的几种设置LineBreakMode方法,主要是通过三个方面:

  • 直接在YYLabel上设置lineBreakMode
  • 在YYTextContainer上设置truncationTokentruncationType
  • 在NSAttributedString上设置lineBreakMode

另外示例代码中橘色的部分是UIlabel设置LineBreak模式的示例,后续YYLabel修正结果以此为参照标准。 设置代码如下:

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];
}
蓝色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


上一篇下一篇

猜你喜欢

热点阅读