iOS——自适应label

来源:互联网 发布:淘宝买ipad知乎 编辑:程序博客网 时间:2024/04/29 03:23

自适应label可以根据文本内容,自动调整大小,代码如下:

- (void)viewDidLoad{    [super viewDidLoad];        self.label1 = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 250, 50)];    self.label2 = [[UILabel alloc] init];        NSString *textStr = @"这是很长的一段话这是很长的一段话这是很长的一段话这是很长的一段话这是很长的一段话这是很长的一段话";    self.label1.text = textStr;    self.label2.text = textStr;        self.label2.lineBreakMode = NSLineBreakByWordWrapping;    self.label2.numberOfLines = 0;        CGSize customLabSize = [textStr sizeWithFont:self.label2.font constrainedToSize:CGSizeMake(290.f, MAXFLOAT) lineBreakMode:self.label2.lineBreakMode];        float customLabHeight = customLabSize.height;    self.label2.frame = CGRectMake(100, 300 , 290.f, customLabHeight);    [self.view addSubview:self.label1];    [self.view addSubview:self.label2];}

效果如图:


0 0
原创粉丝点击