storyboard约束布局
1,如果是从代码层面开始使用Autolayout,需要对使用的View的translatesAutoresizingMaskIntoConstraints的属性设置为NO.
即可开始通过代码添加Constraint,否则View还是会按照以往的autoresizingMask进行计算.
而在Interface Builder中勾选了Ues Autolayout,IB生成的控件的translatesAutoresizingMaskIntoConstraints属性都会被默认设置NO.
2,值得注意的是,添加约束之前一定要将子视图优先addSubview到父视图中,否则在添加约束时会产生编译器警告.
而我们在理解的时候,可以通过这种方式来理解.item1.attribute = multiplier ⨉ item2.attribute + constant,比如看下面的代码
[objc] view plaincopy
UIView *newView = [[UIView alloc]init];
newView.backgroundColor = [UIColor redColor];
[self.view addSubview:newView];
// self.view.translatesAutoresizingMaskIntoConstraints =NO;
newView.translatesAutoresizingMaskIntoConstraints =NO;
NSLayoutConstraint *constraint = nil;
constraint = [NSLayoutConstraint constraintWithItem:newView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeading
multiplier:1.0f
constant:20];
[self.view addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:newView
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTrailing
multiplier:1.0f
constant:-20];
[self.view addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:newView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTop
multiplier:1.0f
constant:80];
[self.view addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:newView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1.0f
constant:-20];
[self.view addConstraint:constraint];