IOS label自适应高度

label自适应高度的非主流方法(用到numberOfLinessizeThatFits:方法),,优点:宽度精准

  UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(150501500)];

  label.font = [UIFont systemFontOfSize:15];

  label.backgroundColor = [UIColor yellowColor];

  label.numberOfLines = 0;

  label.text = @"123456789";

  CGSize size = [label sizeThatFits:CGSizeMake(label.frame.size.widthMAXFLOAT)];

  [label setHeight:size.height];//重新设置lab高度

  //设置lab的行间距和字间距,让字体更美观

  label.attributedText=[self changeSpaceForLabel:label withLineSpace:5.0 WordSpace:0];


  NSLog(@"label.frame = %@",NSStringFromCGRect(label.frame));

  [self.view addSubview:label];


#pragma mark - 设置UILabel的wordSpace间距和lineSpace行距

- (NSAttributedString *)changeSpaceForLabel:(UILabel *)label withLineSpace:(float)lineSpace WordSpace:(float)wordSpace {

    

    NSString *labelText = label.text;

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText attributes:@{NSKernAttributeName:@(wordSpace)}];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

    [paragraphStyle setLineSpacing:lineSpace];

    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];

    return attributedString;

}




你可能感兴趣的:(IOS,资料)