iOS7 NSLayoutConstraint

####iOS7 Programming Cookbook 第三章学习笔记 NSLayoutConstraint

#####Autolayout and the Visual Format Language Introduction

#####ViewController.m

1
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
49
50
51
52
53
54
55
56
57
@interface ViewController ()
@property (nonatomic, strong) UIButton *button1;
@property (nonatomic, strong) UIButton *button2;
@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];

//UIButtonTypeRoundedRect:一个圆角矩形样式按钮
//UIButtonTypeSystem:系统风格的按钮,比如导航栏和工具栏所示
self.button1 = [UIButton buttonWithType:UIButtonTypeSystem];
//正常或者默认状态,,但无论是选择还是启用高亮显示。
[self.button1 setTitle:@"Button 1" forState:UIControlStateNormal];
self.button2 = [UIButton buttonWithType:UIButtonTypeSystem];
[self.button2 setTitle:@"Button 2" forState:UIControlStateNormal];
//返回一个布尔值,用于显示视图的autoresizing面具是转化为基于约束的布局的约束系统。
self.button1.translatesAutoresizingMaskIntoConstraints = NO;
self.button2.translatesAutoresizingMaskIntoConstraints = NO;
// self.button1.frame = CGRectMake(0, 0, 50, 50);
self.button1.backgroundColor = [UIColor redColor];
[self.view addSubview:self.button1];
[self.view addSubview:self.button2];

/*
创建约束。view1.attr1 = view2.attr2 *乘数+常量”
如果方程没有第二个视图和属性,使用零和NSLayoutAttributeNotAnAttribute。
 */

//布局约束,限制项:属性:相关:项:属性:乘数:常数:
NSLayoutConstraint *button1CenterYConstraint = [NSLayoutConstraint constraintWithItem:self.button1 attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];

NSLayoutConstraint *button2CenterYConstraint = [NSLayoutConstraint constraintWithItem:self.button2 attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];

/*
创建约束。view1.attr1 = view2.attr2 *乘数+常量”
如果方程没有第二个视图和属性,使用零和NSLayoutAttributeNotAnAttribute。
 */

NSLayoutConstraint *button1LeftEqualToButton2Right = [NSLayoutConstraint
constraintWithItem:self.button1 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual
toItem:self.button2 attribute:NSLayoutAttributeRight multiplier:1.0f constant:0.0f];

//setPriority:设置优先级,UILayoutPriorityDefaultLow:这是一个按钮的优先级水平拥抱它的内容 250
[button1LeftEqualToButton2Right setPriority:UILayoutPriorityDefaultLow];
/*
创建约束。view1.attr1 = view2.attr2 *乘数+常量”
如果方程没有第二个视图和属性,使用零和NSLayoutAttributeNotAnAttribute。
 */

NSLayoutConstraint *horizontalDistanceBetweenButtonsConstraint = [NSLayoutConstraint constraintWithItem:self.button1 attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.button2 attribute:NSLayoutAttributeLeft multiplier:1.0f constant:200.0f];

//添加约束
[self.view addConstraints:@[button1CenterYConstraint, button2CenterYConstraint, horizontalDistanceBetweenButtonsConstraint, button1LeftEqualToButton2Right]];

}

@end

Reference

坚持原创技术分享,您的支持将鼓励我继续创作!
0%