iOS 多种方式计算label的宽、高度(自适应)

2022-07-01  本文已影响0人  海边的遐想

//label的高度

CGSizetextMaxSize =CGSizeMake(kDeviceWidth,MAXFLOAT);

CGFloatlabelHeight = [self.ybt_help_contentboundingRectWithSize:textMaxSizeoptions:NSStringDrawingUsesLineFragmentOriginattributes:@{NSFontAttributeName: [UIFontsystemFontOfSize:14]}context:nil].size.height;

//求label的宽度

CGSizesize = [labelStrboundingRectWithSize:CGSizeMake(MAXFLOAT, height)options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeadingattributes:@{NSFontAttributeName: font}context:nil].size;

//设置不同字体颜色(富文本)

NSRangerange1 = {0,4};

NSRangerange2 = {4, totalPayStr.length-4};

NSMutableAttributedString*attriStr = [[NSMutableAttributedStringalloc]initWithString:totalPayStr];

//必须设置字体大小才能计算出实际宽度

[attriStrsetAttributes:@{NSForegroundColorAttributeName:Xun_Color(106,106,106),NSFontAttributeName: [UIFontsystemFontOfSize:12]}range:range1];

[attriStrsetAttributes:@{NSForegroundColorAttributeName:Xun_Color(195,0,119),NSFontAttributeName: [UIFontsystemFontOfSize:12]}range:range2];

subLabel.attributedText= attriStr;

CGFloatsubLabelWidth = [attriStrboundingRectWithSize:CGSizeMake(CGFLOAT_MAX,30)options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeadingcontext:nil].size.width;

上一篇 下一篇

猜你喜欢

热点阅读