UILabel如何使用sizeToFit正确适配行数

sizeToFit方法,是UIView的一个系统方法,苹果文档如下描述:

- (void)sizeToFit

Description

Resizes and moves the receiver view so it just encloses its subviews.


Call this method when you want to resize the current view so that it uses the most appropriate amount of space. Specific UIKit views resize themselves according to their own internal needs. In some cases, if a view does not have a superview, it may size itself to the screen bounds. Thus, if you want a given view to size itself to its parent view, you should add it to the parent view before calling this method.

You should not override this method. If you want to change the default sizing information for your view, override the sizeThatFits: instead. That method performs any needed calculations and returns them to this method, which then makes the change.

Availability

iOS (2.0 and later)


这个方法,会自动调整view的bounds,使用最小、符合需求的区域大小。


猜想这个方法用来计算label的宽高会很方便,但是一开始未达到效果,代码如下

    UIView *view1 = [[UIView alloc]init];

    view1.frame =CGRectMake(100,100, 200, 200);

    view1.backgroundColor = [UIColor grayColor];

    [self.view addSubview:view1];

    

    UILabel *label = [[UILabel alloc]init];

    label.frame =CGRectMake(0,0,200, 200);

    label.backgroundColor = [UIColor redColor];

    [view1 addSubview:label];

    label.text =@"1dsafafasfasfasfafasfdsafasdfsadfsafdsafasfdsf";

    [label sizeToFit];


效果如下:



这个label为什么没有根据view1的宽度来适配呢?原来label的numberOfLines默认为1,此时sizeToFit不改变label的行数。

增加一行代码:

label.numberOfLines = 0;//设置为0,sizeToFit会自动调整行数


效果如下:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值