美文网首页
UILabel 内容多行显示行间距,单行屏蔽行间距

UILabel 内容多行显示行间距,单行屏蔽行间距

作者: 无迹天空 | 来源:发表于2020-10-09 16:23 被阅读0次

    问题描述

    使用富文本设置行间距后,当文字内容只显示一行时,Label 内部显示多余的行间距,如下图所示:


    处理前.png

    初始代码(包含行间距)代码如下:

    - (void)testBeginLabel
    {
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        titleLabel.numberOfLines = 0;
        titleLabel.font = [UIFont systemFontOfSize:14];;
    
        NSString *title = @"这个是一行标题";
    
        CGFloat titleMaxWidth = 320; // 设置最大宽度
        NSMutableAttributedString *attributedTitle = [[NSMutableAttributedString alloc] initWithString:title];
        NSMutableParagraphStyle *paragraphStyleTitle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyleTitle setLineSpacing:5]; // 设置行间距
        [attributedTitle addAttribute:NSParagraphStyleAttributeName
                                value:paragraphStyleTitle
                                range:NSMakeRange(0, [title length])];
        [titleLabel setAttributedText:attributedTitle];
    
        // 动态计算UILabel 内容显示大小
        CGSize size = [titleLabel sizeThatFits:CGSizeMake(titleMaxWidth, MAXFLOAT)];
        // 设置frame
        titleLabel.frame = CGRectMake(10, 10, size.width, size.height);
        [self.contentView addSubview:titleLabel];
    }
    

    解决方式

    第 1 步:使用 sizeToFit 方法判断能否一行显示
    第 2 步:如果能一行显示,就不再使用 NSMutableParagraphStyle 设置行间距,否则再设置行间距

    代码处理如下:

    - (void)testLabelFixed
    {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:14];
    
        NSString *title = @"这个是一行标题";
    
        CGFloat titleMaxWidth = 320; // 设置最大宽度
        
        label.text = title;
        [label sizeToFit];
        if (label.frame.size.width > titleMaxWidth) {
            // 超过一行设置行间距
            NSMutableAttributedString *attributedTitle = [[NSMutableAttributedString alloc] initWithString:title];
            NSMutableParagraphStyle *paragraphStyleTitle = [[NSMutableParagraphStyle alloc] init];
            [paragraphStyleTitle setLineSpacing:5];
            [attributedTitle addAttribute:NSParagraphStyleAttributeName
                                    value:paragraphStyleTitle
                                    range:NSMakeRange(0, [title length])];
            [label setAttributedText:attributedTitle];
            CGSize size = [label sizeThatFits:CGSizeMake(titleMaxWidth, MAXFLOAT)];
            label.frame = CGRectMake(10, 10, size.width, size.height);
        } else {
            label.frame = CGRectMake(10, 10, label.frame.size.width, label.frame.size.height);
        }
        [self.contentView addSubview:label];
    }
    

    处理后效果如下:


    处理后.png

    总结

    无复杂API,简单方式处理

    相关文章

      网友评论

          本文标题:UILabel 内容多行显示行间距,单行屏蔽行间距

          本文链接:https://www.haomeiwen.com/subject/vsvlpktx.html