美文网首页
一个Label,某行居中展示。

一个Label,某行居中展示。

作者: follow_er | 来源:发表于2022-02-16 15:00 被阅读0次

    需求样式如下:


    image.png

    实现方式,在label上使用富文本展示

    NSString *endTime = @"2022 - 02 - 22 13:56";
    NSString *endTimeLine = [NSString stringWithFormat:@"到期时间: %@", endTime];
    NSString *str = [NSString stringWithFormat:@"现在市场不太友好,动不动就跌几天。主流币都跌百分之五十左右了。\n\n%@",endTimeLine];
    if (str.length) {
                UILabel *lab = [[UILabel alloc] init];
                CGFloat labMaxW = 300;
                CGFloat labH = ceilf(lab.font.lineHeight);
                CGFloat labW = ceilf([str boundingRectWithSize:fittingSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attr context:nil].size.width);
                if (labW > labMaxW) {
                    labW = labMaxW;
                    labH = ceilf([str boundingRectWithSize:fittingSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attr context:nil].size.height);
                }
                [lab setBounds:CGRectMake(0, 0, labW, labH)];
                NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:str];
                NSRange range = [str rangeOfString: endTime];
                [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range: range];
                
                NSRange rangeEndTimeLine = [str rangeOfString: endTimeLine];
                NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
                paragraphStyle.alignment = NSTextAlignmentCenter;
                [attriStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range: rangeEndTimeLine];
                lab.attributedText = attriStr;
            }
    

    相关文章

      网友评论

          本文标题:一个Label,某行居中展示。

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