需求样式如下:
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;
}
网友评论