iOS:UIButton自动版式大小为零 [英] iOS: UIButton Autolayout size is zero

查看:81
本文介绍了iOS:UIButton自动版式大小为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用自动布局,我想了解为什么会发生以下情况:创建一个简单的UIButton并设置其标题.但是,即使我希望设置视图的固有内容大小并因此正确获取其框架,该按钮的框架也会显示(0,0,0,0).我该怎么做才能获取按钮的帧值?

Using autolayout I want to understand why the following happens: Creating a simple UIButton and setting its title. However, even though I expect the intrinsic content size of the view to be set and hence get its frame properly - the frame of the button is showing (0, 0, 0, 0). What do I have to do to get the frame value of the button ?

-(void)viewDidLoad {

    [super viewDidLoad];

    UIButton *button = [[UIButton alloc] init];

    [button.titleLabel setText:@"My button"];

    //button frame is zero

}

但是,如果我要这样做,那么事情将会按预期进行:

Yet if I am to do that, then things work as expected:

-(void)viewDidLoad {

    [super viewDidLoad];

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

    [label setText:@"My label"];

    [label sizeToFit];

    //label frame has the expected width and height

}

推荐答案

仅在布局通过后,自动布局才会设置视图框架,这是一个循环的过程,不被称为每次添加视图或修改约束的时候,这就是为什么有时需要在特定视图上调用-setNeedsLayout.
另一点是,如果您不使用界面生成器或以编程方式创建约束,则自动布局会自动将视图自动调整大小的蒙版转换为约束(-translatesAutoresizingMaskIntoConstraints属性).
在这种情况下,如果设置文本,则将强制视图表达其内在内容的大小,这基本上是标签的大小,如果内在内容的大小与它赢得的其他约束不冲突,但是您只能问布局通过后的按钮大小.调用相同方法的超类后,尝试检查.viewDidLayout中的按钮大小

Autolayout sets views frame only after a layout pass, it's something that has cycle and is not called evertytime you add a view or modify constraints, that's why sometimes you need to call -setNeedsLayout on a particular view.
The other point is that if you do not create constraints using interface builder or programmatically, autolayout automatically converts the view autoresizing masks into constraints (-translatesAutoresizingMaskIntoConstraints property).
In this case if you set a text, you are forcing the view to express its intrinsic content size, that basically is the size of the label, if the intrinsic content size doesn't conflict to other constraints it wins, but you can only ask the button size after the layout pass. Try to check the button size inside .viewDidLayout after the call of the same method to the super class

这篇关于iOS:UIButton自动版式大小为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆