代码 自动布局
//ios6 : Auto Layout
self.view1 = [[UIView alloc] init];
// self.view1 = [[UIView alloc] initWithFrame:CGRectMake( 0, 100, 200, 80)];
//[tConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"|-50-[_view1(==blueView)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_view1)]];
_view1.backgroundColor = [UIColor redColor];
//来禁用“古老的”springs and struts方法。这个属性是为了向后兼容。
[_view1 setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:_view1];
//创建约束 添加约束项
// A = B*m + c; / _view1.NSLayoutAttributeLeading = self.view.NSLayoutAttributeLeading * 1.0f + 20.f
NSLayoutConstraint *constrant = [NSLayoutConstraint constraintWithItem:_view1 //1,
attribute:NSLayoutAttributeLeading //对齐矩形前沿
relatedBy:NSLayoutRelationEqual
toItem:self.view //2,
attribute:NSLayoutAttributeLeading //对齐矩形前沿
multiplier:1.0f
constant:22.f];
//添加
constrant = [NSLayoutConstraint constraintWithItem:_view1
attribute:NSLayoutAttributeTop //距顶端
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTop
multiplier:1.0f
constant:30.f];
constrant = [NSLayoutConstraint constraintWithItem:_view1
attribute:NSLayoutAttributeWidth //距顶端
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeWidth
multiplier:1.0f
constant:30.f];
constrant = [NSLayoutConstraint constraintWithItem:_view1
attribute:NSLayoutAttributeHeight //距顶端
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:1.0f
constant:30.f];
//为一组视图添加约束 先建立一个字典
NSDictionary *viewsDic = NSDictionaryOfVariableBindings(_view1);//创建一个字典中键是对应的字符串表示值的变量名。
//靠左边50, 宽200, 右边不约束,
//[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-50-[_view1(==200)]" options:0 metrics:0 views: viewsDic]];
//靠上边50, 高200, 下边不约束
//[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-50-[_view1(==200)]" options:0 metrics:0 views: viewsDic]];
// 宽200, 右右不约束,
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[_view1(==200)]" options:0 metrics:0 views: viewsDic]];
//靠上边100, 高100, 下边不约束
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-100-[_view1(==100)]" options:0 metrics:0 views: viewsDic]];
//水平方向 居中
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_view1
attribute:NSLayoutAttributeCenterX //距顶端
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0f
constant:0.f]];
//竖直方向
//[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_view1
// attribute:NSLayoutAttributeCenterY //距顶端
// relatedBy:NSLayoutRelationEqual
// toItem:self.view
// attribute:NSLayoutAttributeCenterY
// multiplier:1.0f
// constant:-80.f]];