码迷,mamicode.com
首页 > 其他好文 > 详细

自动布局(AutoLayout)使用

时间:2015-05-28 11:03:06      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

/*1. 创建控件,并添加到当前的View中*/
self.rightButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.rightButton.translatesAutoresizingMaskIntoConstraints = NO;
[self.rightButton setTitle:@"RightButton" forState:UIControlStateNormal];
[self.view addSubview:self.rightButton];

/*2.创建控件的X轴方向的约束 */
NSLayoutConstraint *rightButtonXConstraint = [NSLayoutConstraint constraintWithItem:self.rightButton
                                                                          attribute:NSLayoutAttributeCenterX
                                                                          relatedBy:NSLayoutRelationGreaterThanOrEqual
                                                                             toItem:superview
                                                                          attribute:NSLayoutAttributeCenterX
                                                                         multiplier:1.0
                                                                           constant:-100.0f];
/*3. 创建控件的Y轴方向的约束 */
NSLayoutConstraint *centerYMyConstraint = [NSLayoutConstraint constraintWithItem:self.rightButton
                                                                       attribute:NSLayoutAttributeCenterY
                                                                       relatedBy:NSLayoutRelationGreaterThanOrEqual
                                                                          toItem:superview
                                                                       attribute:NSLayoutAttributeCenterY
                                                                      multiplier:1.0f
                                                                        constant:0.0f];
// 将约束条件添加到父View
[superview addConstraints:@[centerYMyConstraint, rightButtonXConstraint]];

上面的代码实现了控制 rightButton以默认大小,显示在superView的中心位置,水平方向偏左100.0。

这里主要用到了NSLayoutConstraint的:

constraintWithItem:(id)view1 attribute:(NSLayoutAttribute)attr1 relatedBy:(NSLayoutRelation)relation toItem:(id)view2 attribute:(NSLayoutAttribute)attr2 multiplier:(CGFloat)multiplier constant:(CGFloat)c

的属性

view1:需要约束的视图

attr1:需要约束的位置(上下左右中心... )

relation:相关性(>=, = , <=,  一般用=就可以)

view2:目标视图(参照视图)

attr2: 参照位置

multiplier:参考值的倍数

c:偏移量


***注意***

self.rightButton.translatesAutoresizingMaskIntoConstraints = NO;

这句要加上,不然约束无效。


参考文章

IOS自动布局

コードでAutolayout

自动布局(AutoLayout)使用

标签:

原文地址:http://my.oschina.net/lavzchen/blog/420879

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!