用代码实现AutoLayout 可以避免复杂的计算 不过还是需要很强的逻辑思维来进行编辑
首先是要创建视图 要记住先subView才能添加约束
self.title = @"使用AutoLayout的方式";
UIView *purpleView = [[UIView alloc]init];
purpleView.backgroundColor = [UIColor purpleColor];
//禁止将AutoresizingMask转化为Contraints
purpleView.translatesAutoresizingMaskIntoConstraints = false;
[self.view addSubview:purpleView];
//添加Width的约束
NSLayoutConstraint *widthConstraints = [NSLayoutConstraint constraintWithItem:purpleView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:150];
[purpleView addConstraint:widthConstraints];
//添加height的约束
NSLayoutConstraint *heightConstraints = [NSLayoutConstraint constraintWithItem:purpleView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:150];
[purpleView addConstraint:heightConstraints];
// 添加 left 约束
NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:purpleView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:100];
[self.view addConstraint:leftConstraint];
// 添加 top 约束
NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:purpleView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:200];
[self.view addConstraint:topConstraint];
7个参数意思 第一个 添加约束的视图 第二个 是什么约束 第三个与参照约束控件的关系 第四个参照控件 第五个参照控件的约束 第六个 乘数 第七个 在做完乘数后再加上这个常量值
感觉比较的繁琐 OC版提供了
Masonry这个框架
https://github.com/SnapKit/Masonry
创建约束可以这样
//创建长宽为100 中心与视图中心对齐的约束
[purpleView mas_makeConstraints:^(MASConstraintMaker *make) {
make.size.mas_equalTo(CGSizeMake(100, 100));
make.center.mas_equalTo(self.view);
}];
//长宽均为100 粘着view的右下角
[purpleView mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.equalTo(@100);
make.height.equalTo(@100);
//加一个偏移量
make.right.equalTo(self.view).with.offset(-16);
make.bottom.equalTo(self.view);
}];
swift版也提供了SnapKit这个框架
https://github.com/SnapKit/SnapKit
box.snp_makeConstraints { (make) in
make.width.height.equalTo(50)
make.center.equalTo(self.view)
}
个人感觉还不如Sb或者xib简单
参考网站:http://mp.weixin.qq.com/s?__biz=MzAxMzE2Mjc2Ng==&mid=2652154923&idx=1&sn=ad90dacb11520845ac58a0f09b75abe4&scene=0#wechat_redirect