ios开发之lable根据文字自适应行高和换行

前言:开发中难免会遇到设置lable根据文字来调整高度和换行,具体做法如下.

sizethatfits方法
  1. 设置lable的frame,numberofLines,字体等.
 UILabel *carTypeLN = [[UILabel alloc]init];
carTypeLN.frame = CGRectMake(margin+((margin+width)*lie), (row*(height+topMargin)), width,height);
  1. 根据本身的view的frame,对lable的frame进行适配.
    carTypeLN.textAlignment = NSTextAlignmentCenter;
    carTypeLN.textColor = HEX_COLOR(kColor_Flag_GrayDark);
    carTypeLN.backgroundColor = HEX_COLOR(kColor_BG_white);
    carTypeLN.font = [UIFont systemFontOfSize:13];
    carTypeLN.text = types[i];
    CGSize size = [self sizeThatFits:CGSizeMake(carTypeLN.frame.size.height, MAXFLOAT)];
    CGRect frame = carTypeLN.frame;
    frame.size.height = size.height;
    [carTypeLN setFrame:frame];
    [self addSubview:carTypeLN];
    carTypeLN.numberOfLines = 0;

根据lable的文字以及font,对特定的宽度适配出符合该段文字的高度,该种方法比较灵活.

    CGSize labelSize = [self.contentLabel.text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-130, 10000) options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesDeviceMetrics|NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingTruncatesLastVisibleLine attributes:@{NSFontAttributeName:self.contentLabel.font} context:nil].size;

你可能感兴趣的:(ios开发之lable根据文字自适应行高和换行)