在Objective-C中以编程方式添加约束 [英] Adding constraints programmatically in Objective-C

查看:150
本文介绍了在Objective-C中以编程方式添加约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以编程方式向UIButton添加一些约束. 我需要它使它在水平方向上居中以超级视图,在垂直方向上居中以超级视图,宽高比为其超级视图以及宽高比为自己.

I need to add some constraints to a UIButton programmatically. I need it to have it centred horizontally to superview, centred vertically to superview, aspect ratio to its superview and aspect ratio to self.

有人可以帮我吗?

谢谢.

推荐答案

我将为您提供帮助,以便您可以了解总体思路,否则请使用Larme提供的文档.

I'll get the ball rolling for you so you can see the general idea, otherwise use the documentation as provided by Larme.

在您的超级视图(可能是您的视图控制器)中添加约束.

Add the constraint in your superview (probably your view controller).

NSLayoutConstraint *centreHorizontallyConstraint = [NSLayoutConstraint
                                      constraintWithItem:self.uiButton
                                      attribute:NSLayoutAttributeCenterX
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeCenterX
                                      multiplier:1.0
                                      constant:0];

[self.view addConstraint:centreHorizontallyConstraint];

因此,正如您所看到的,我们说的是约束UIButton的center x属性,也就是没有附加偏移量(乘数设置为1.0和常数0)的View Controllers视图的center x属性.

So as you can see we are saying constraint the centre x attribute of UIButton too the centre x attribute of the View Controllers view with no additional offsets (multiplier set to 1.0 and constant 0).

请确保将其添加到视图控制器的视图中,而不是按钮中,因为此时按钮尚未布置,因此您无法为其添加约束! (如果我在这里错了,请有人纠正我).我将约束添加到viewDidLoad方法中.

Make sure you add it to your view controller's view not the button because the button has not been laid out at this point and therefore you cannot add a constraint to it! (Please someone correct me if I'm wrong here). I add my constraints in the viewDidLoad method.

这篇关于在Objective-C中以编程方式添加约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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