iOS UILabel自适应

sizeToFit:计算出最优的size,会改变已经设置好的frame。

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 0, 0)];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:13];
    label.textColor = [UIColor redColor];
    label.numberOfLines = 0;
    label.text = @"飞雪连天射白鹿,笑书神侠倚碧鸳";
    [self.view addSubview:label];
    [label sizeToFit];
    NSLog(@"%@",NSStringFromCGRect(label.frame));
    
    2018-12-26 12:57:11.166520+0800 UILabelFit[77988:3110803] {{100, 100}, {199, 15.666666666666666}}

sizeThatFits:会计算出最优的size 但是不会改变已经设置的frame。

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 0, 0)];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:13];
    label.textColor = [UIColor redColor];
    label.numberOfLines = 0;
    label.text = @"飞雪连天射白鹿,笑书神侠倚碧鸳";
    [self.view addSubview:label];
    CGSize size = [label sizeThatFits:CGSizeZero];
    NSLog(@"%@",NSStringFromCGSize(size));
    2018-12-26 14:17:42.276945+0800 UILabelFit[78627:3155105] {199, 15.666666666666666}

你可能感兴趣的:(iOS UILabel自适应)