iOS11、计算label文字的高度

2019-01-17  本文已影响8人  echo海猫

1、通过sizeThatFits

// return 'best' size to fit given size. does not actually resize view. Default is return existing view size
- (CGSize)sizeThatFits:(CGSize)size;   
(返回“最佳”大小以适合给定大小。实际上不调整视图的大小。默认值是返回现有视图大小)  

使用:CGFloat height = 0
height  += [self.requestTimeL sizeThatFits:size].height;

2、带段落的换行的文字

-(CGFloat)textHeight:(NSString *)str{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
//Attribute传和label设定的一样
    NSDictionary * attributes = @{
                                  NSFontAttributeName:[UIFont systemFontOfSize:12.f],
                                  NSParagraphStyleAttributeName: paragraphStyle
                                  };
//这里的size,width传label的宽,高默认都传MAXFLOAT
    CGSize textRect = CGSizeMake([UIScreen mainScreen].bounds.size.width - 30, MAXFLOAT);
    CGFloat textHeight = [str boundingRectWithSize: textRect
                                           options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                        attributes:attributes
                                           context:nil].size.height;
    return textHeight;
}

3、

上一篇 下一篇

猜你喜欢

热点阅读