ios label的一些设置

时间:2023-02-01 09:29:51

一.根据文本长度设置label的宽高和字体大小

  NSString *str = @"天将降大任于斯人也,必先苦其心志.天将降大任于斯人也,必先苦其心志.";

     CGRect tempRect = [str boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-40,2000)           options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];

    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(20,100, tempRect.size.width, tempRect.size.height)];
    label.text = str;
    label.numberOfLines = 1;
    label.adjustsFontSizeToFitWidth = YES;      //根据文本宽度设置字体大小
    [self.view addSubview:label];