iOS label根据显示内容自适应大小

来源:互联网 发布:mac steam 目录 编辑:程序博客网 时间:2024/05/16 08:54
- (void)setupLabel { 2     //准备工作 3     UILabel *textLabel = [[UILabel alloc] init]; 4     textLabel.font = [UIFont systemFontOfSize:16]; 5     NSString *str = @"222222222222222222222222222222222222222222"; 6     textLabel.text = str; 7     textLabel.backgroundColor = [UIColor redColor]; 8     textLabel.numberOfLines = 0;//根据最大行数需求来设置    9     textLabel.lineBreakMode = NSLineBreakByTruncatingTail;10     CGSize maximumLabelSize = CGSizeMake(100, 9999);//labelsize的最大值11     //关键语句12     CGSize expectSize = [textLabel sizeThatFits:maximumLabelSize];13     //别忘了把frame给回label,如果用xib加了约束的话可以只改一个约束的值14     textLabel.frame = CGRectMake(20, 70, expectSize.width, expectSize.height);15     [self.view addSubview:textLabel];
      //也可以用
       

textLabel.adjustsFontSizeToFitWidth = YES;

textLabel.numberOfLines = 0;

16 }
原创粉丝点击