####iOS7 Programming Cookbook 第三章学习笔记 NSLayoutConstraint
#####Placing UI Components in the Center of the Screen
#####ViewController.m1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@interface ViewController ()
@property (nonatomic, strong) UIButton *button;
@end
@implementation ViewController
- (void)viewDidLoad{
[super viewDidLoad];
/*创建button*/
//类型
self.button = [UIButton buttonWithType:UIButtonTypeSystem];
self.button.translatesAutoresizingMaskIntoConstraints = NO;
//button,tittle,state
[self.button setTitle:@"Button" forState:UIControlStateNormal];
//添加到view
[self.view addSubview:self.button];
UIView *superview = self.button.superview;
/* 2) 创建布局约束 把按钮放在中心 */
NSLayoutConstraint *centerXConstraint =
[NSLayoutConstraint constraintWithItem:self.button//约束item
attribute:NSLayoutAttributeCenterX//对象的中心沿着x轴的对齐矩形。
relatedBy:NSLayoutRelationEqual//约束要求的第一属性是修改后的第二属性相等。
toItem:superview
attribute:NSLayoutAttributeCenterX//对象的中心沿着x轴的对齐矩形。
multiplier:1.0f//乘数
constant:0.0f];//常数
/* 3) 创建布局约束 将按钮放在中心垂直 */
NSLayoutConstraint *centerYConstraint =
[NSLayoutConstraint constraintWithItem:self.button
attribute:NSLayoutAttributeCenterY//对象的中心沿着y轴的对齐矩形。
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeCenterY
multiplier:1.0f
constant:0.0f];
/* 添加该约束 */
[superview addConstraints:@[centerXConstraint, centerYConstraint]];
}
@end