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

来源:互联网 发布:怎么用数据库做购物车 编辑:程序博客网 时间:2024/06/05 03:56

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
原创粉丝点击