美文网首页
UILabel及富文本相关

UILabel及富文本相关

作者: 梦回蓝桥 | 来源:发表于2018-06-12 11:13 被阅读91次

这里主要分两部分来介绍文本相关的内容
1,自己封装能够满足需求的类来实现需求
2,使用三方库(如YYText)实现比较复杂的需求
宗旨:能自己实现的就不要去用别人的东西.

自行封装满足需求的情况:如下图


WechatIMG9058.jpeg

需求:行间距为10,label的最后一行不要行间距,显示行数有时全部显示,有时只显示特定行数(如图)
实现思路:写一个UILabel的分类“UILabel+SX.h”并为其添加两个属性lineSpacing(行间距)及ConstrainedWidth(行宽),开放下面的方法接口用于实现label的高度计算及各属性设置

- (CGFloat)getTextHeightWithNumberOfLines:(NSInteger)numberOfLines lineSpacing:(CGFloat)lineSpacing constrainedWidth:(CGFloat)constrainedWidth
{
    if (!self.text || self.text.length == 0) {
        return 0;
    }
    self.numberOfLines = numberOfLines;
    self.LineSpacing = lineSpacing;
    self.ConstrainedWidth = constrainedWidth;
    CGSize textSize = [self.text textSizeWithFont:self.font numberOfLines:self.numberOfLines lineSpacing:self.LineSpacing constrainedWidth:constrainedWidth];

    //单行的情况
    if (fabs(textSize.height - self.font.lineHeight) < 0.00001f) {
        self.LineSpacing = 0.0f;
    }

    //设置文字的属性
    NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:self.text];

    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:self.LineSpacing];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;//结尾部分的内容以……方式省略
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.text length])];
    //注释
    [attributedString addAttribute:NSForegroundColorAttributeName value:self.textColor range:NSMakeRange(0, [self.text length])];
    [attributedString addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, [self.text length])];
    [self setAttributedText:attributedString];

    return textSize.height;
}


其中

CGSize textSize = [self.text textSizeWithFont:self.font numberOfLines:self.numberOfLines lineSpacing:self.LineSpacing constrainedWidth:constrainedWidth];


此方法是创建的NSString的分类"NSString+SX.h"中的方法,用于计算label.text的真实size

- (CGSize)textSizeWithFont:(UIFont*)font
         numberOfLines:(NSInteger)numberOfLines
           lineSpacing:(CGFloat)lineSpacing
      constrainedWidth:(CGFloat)constrainedWidth{

    if (self.length == 0) {
        return CGSizeZero;
    }
    CGFloat oneLineHeight = font.lineHeight;
    CGSize textSize = [self boundingRectWithSize:CGSizeMake(constrainedWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;

    CGFloat rows = textSize.height / oneLineHeight;
    CGFloat realHeight = oneLineHeight;
    // 0 不限制行数
    if (numberOfLines == 0) {
        if (rows >= 1) {
            realHeight = (rows * oneLineHeight) + (rows - 1) * lineSpacing;
        }
    }else{
        if (rows > numberOfLines) {
            rows = numberOfLines;
        }
        realHeight = (rows * oneLineHeight) + (rows - 1) * lineSpacing;
    }
    return CGSizeMake(constrainedWidth, realHeight);
}


简单的使用如下:

self.customLabel1 = [[UILabel alloc]init];
self.customLabel1.text = @"此label用于演示文本及富文本按照特定行数显示或全部显示的问题,此label用于演示文本及富文本按照特定行数显示或全部显示的问题,此label用于演示文本及富文本按照特定行数显示或全部显示的问题,此label用于演示文本及富文本按照特定行数显示或全部显示的问题,此label用于演示文本及富文本按照特定行数显示或全部显示的问题,";
self.customLabel1.font = [UIFont systemFontOfSize:16];
// NumberOfLines :展示的行数(0时全部显示)、行间距、行宽获取label的真实高度
CGFloat customLabel1Height = [self.customLabel1 getTextHeightWithNumberOfLines:3 lineSpacing:10 constrainedWidth:ScreenWidth - 30];
self.customLabel1.frame = CGRectMake(15, 50, ScreenWidth - 30, customLabel1Height);
[scrollView addSubview:self.customLabel1];


效果如下(numberOfLines=3、numberOfLines=0)

WechatIMG9163 1.png

然后看看富文本的需求:效果如下(红色背景部分)


WechatIMG9067.png

除了基本设置之外,还有超链接(点击蓝色字体执行相应事件)、图片等相应的富文本要求

/* YYLabel */
NSString *text = @"无论你高考考了多少分,能不能去你想去的大学,都不用担心,你能去的地方,一定会带给你预想不到的惊喜,你会遇见一些人,觉得相见恨晚,经历一些事,铭记终生,如果那年我们多对或者多错两道题,那么我们会不会在不同的地方,认识完全不同的人,做着完全不同的事,错过我们现在所拥有的一切,高考的迷人之处不是得偿所愿,而是阴差阳错";
NSMutableAttributedString *aString = [[NSMutableAttributedString alloc]initWithString:text];

// 设置整段文本size
aString.yy_font = [UIFont systemFontOfSize:16];
// 设置整段文本行间距
aString.yy_lineSpacing = 10;
// 设置整段文本下划线
//aString.yy_underlineStyle = NSUnderlineStyleSingle;
// 获得range 并做相应的设置
NSRange range1 = [text rangeOfString:@"相见恨晚"];
//[aString yy_setTextUnderline:[YYTextDecoration decorationWithStyle:YYTextLineStyleSingle] range:range];
[aString yy_setFont:[UIFont systemFontOfSize:22] range:range1];
//超链接的设置
[aString yy_setTextHighlightRange:range1 color:[UIColor colorWithHexString:@"56bcff"] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
    SXLog(@"您点击了相见恨晚的超链接");
}];

//NSRange range2 = [text rangeOfString:@"高考的迷人之处不是得偿所愿"];
NSRange range2 = NSMakeRange(text.length - 20, 13);
[aString yy_setFont:[UIFont systemFontOfSize:22] range:range2];
[aString yy_setTextHighlightRange:range2 color:[UIColor colorWithHexString:@"56bcff"] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
    SXLog(@"您点击了得偿所愿的超链接");
}];

/* 加入图文混排 */
NSMutableAttributedString *attachment = nil;
// 嵌入 UIImage
UIImage *image = [UIImage imageNamed:@"addcenter"];
attachment = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:image.size alignToFont:[UIFont systemFontOfSize:16] alignment:YYTextVerticalAlignmentCenter];
[aString appendAttributedString: attachment];

//在图片后面再插入一个人label 
NSMutableAttributedString *xinzengText = [[NSMutableAttributedString alloc] initWithString:@"我是用于测试新增文本的label"];
xinzengText.yy_font = [UIFont systemFontOfSize:16];
xinzengText.yy_color = [UIColor blueColor];
[aString appendAttributedString:xinzengText];


// 使用YYLabel进行渲染
YYLabel *FWBLabel = [[YYLabel alloc]init];
FWBLabel.backgroundColor = [UIColor redColor];
FWBLabel.attributedText = aString;

//FWBLabel.textAlignment = NSTextAlignmentCenter;//导致高亮排版有问题
//FWBLabel.numberOfLines = 0;
[scrollView addSubview:FWBLabel];

// 计算文本尺寸 进行布局
CGSize maxSize = CGSizeMake(ScreenWidth - 30, MAXFLOAT);
YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:maxSize text:aString];
FWBLabel.textLayout = layout;
CGFloat fwbHeight = layout.textBoundingSize.height;
FWBLabel.frame = CGRectMake(15, CGRectGetMaxY(self.customLabel3.frame)+20, ScreenWidth - 30, fwbHeight);


点击YYText查看详细介绍及使用!

相关文章

网友评论

      本文标题:UILabel及富文本相关

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