初步学习, 简单记录一下不同约束方法的使用.
首先, Masonry是一个第三个框架, 我们可以调用它已经定义好的约束方法, 这里使用Cocoapods导入该框架
platform :ios, '8.0'
target 'MasoryJJ' do
pod 'Masonry'
end
然后, 在工程中到入头文件
头文件 #import <Masonry.h>
我在查阅资料的时候, 发现了两个宏定义:
#define MAS_SHORTHAND_GLOBALS
添加该宏,那么mas_equalTo和equalTo就没有区别,注意:这个宏一定要添加到#import "Masonry.h"前面
#define MAS_SHORTHAND
如果添加了上面的宏,mas_width也可以写成width
mas_width : 是一个属性值, 当做equalTo的参数
width : make对象的一个属性
* 我验证后的效果是, 第二个宏是有效果的, 第一个没有得到证明 , 继续努力
下面为实现效果代码
***约束一
UIView *backView = [[UIView alloc] init];
backView.backgroundColor = [UIColor colorWithRed:0.429 green:0.574 blue:1.000 alpha:1.000];
[self.view addSubview:backView];
[backView mas_makeConstraints:^(MASConstraintMaker *make) {
//大小
make.size.mas_equalTo(CGSizeMake(300, 200));
//坐标
make.centerX.equalTo(self.view);
make.top.equalTo(self.view).with.offset(30);
}];
*** 约束二
UIView *leftView = [[UIView alloc] init];
leftView.backgroundColor = [UIColor redColor];
[self.view addSubview:leftView];
[leftView mas_makeConstraints:^(MASConstraintMaker *make) {
# 这里用的是 mas_equalTo
make.left.mas_equalTo(backView.mas_left).with.offset(10);
make.top.mas_equalTo(backView.mas_top).with.offset(10);
make.right.mas_equalTo(backView.centerX).with.offset(-10);
make.bottom.mas_equalTo(backView.centerY).with.offset(-10);
}];
*** 约束三
UIView *rightView = [[UIView alloc]init];
rightView.backgroundColor = [UIColor yellowColor];
[self.view addSubview:rightView];
[rightView mas_makeConstraints:^(MASConstraintMaker *make) {
# 这里是添加宏定义后, 使用 equalTo (没有添加宏定义也可以使用)
make.right.equalTo(backView.mas_right).with.offset(-10);
make.left.equalTo(backView.mas_centerX).with.offset(10);
make.top.equalTo(backView.mas_top).with.offset(10);
make.bottom.equalTo(backView.centerY).with.offset(-10);
}];
*** 约束三
UIView *leftView2 = [[UIView alloc] init];
leftView2.backgroundColor = [UIColor orangeColor];
[self.view addSubview:leftView2];
[leftView2 mas_makeConstraints:^(MASConstraintMaker *make) {
#这里是添加宏定义后, mas_height == height
make.right.equalTo(leftView.right);
make.left.equalTo(leftView.left);
make.top.equalTo(leftView.bottom).with.offset(10);
make.height.equalTo(leftView.height);
}];
// //更新约束
// [leftView2 updateConstraints:^(MASConstraintMaker *make) {
//
// //???
// make.right.equalTo(backView.right).offset(-10);
//
// }];
//
// //删除指定控件的约束
// [leftView2 remakeConstraints:^(MASConstraintMaker *make) {
//
// }];
***约束四
UIView *botton = [[UIView alloc] init];
botton.backgroundColor = [UIColor greenColor];
[self.view addSubview:botton];
[botton mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(backView.left);
make.top.equalTo(backView.bottom).offset(20);
make.width.equalTo(backView.width);
make.height.equalTo(backView.height);
}];
*** 约束五
UIView *bottonIn = [[UIView alloc] init];
bottonIn.backgroundColor = [UIColor blueColor];
[botton addSubview:bottonIn];
[bottonIn mas_makeConstraints:^(MASConstraintMaker *make) {
# 相对于父视图来说的内边距设置
make.edges.mas_offset(UIEdgeInsetsMake(10, 10, 10, 10));
}];