使用CocoaPods引入Masonry第三方库
1. 搜索源是否存在:
pod search masonry
如果有的话会帮我们标识需要的库
如果第一次使用,会出现:Setting up CocoaPods master repo
这个会跑很长的时间,是在配置CocoaPods,要一直翻着墙。
在一大堆显示后有Setup completed
表示配置完成,下次使用就很快了。
2. 创建工程:
在创建一个项目工程后,cd + 拖拽你的项目文件将路径导入
cd /Your Project FilePath
touch PodFile
然后打开工程所在文件,会发现多出一个PodFile文件
打开PodFiled文件,把下面内容复制进去并保存
platform :ios, '7.0'
target '你的项目工程名字' do
pod 'Masonry'
end
最后一步是在终端读取PodFile找到相关类库下载并自动集成到项目中,同时生成新的*.xcworkspace文件:
pod install
然后就搞定了,之后使用时就打开后缀名为*.xcworkspace
的文件
Masonry的基本使用
mas_makeConstraints() 添加约束
mas_remakeConstraints() 移除之前的约束,重新添加新的约束
mas_updateConstraints() 更新约束
dividedBy() 除以某个量,用以实现按比例设置约束
multipliedBy() 乘以某个量
offset() 括号里填写偏差量
equalTo() 如果括号里填写数组,可以实现对多个控件添加同一约束;
如果equalTo()内填写的内容相同,可以使用一个语句来添加多条约束
1.尺寸:width、height、size
2.边界:left、leading、right、trailing、top、bottom
3.中心点:center、centerX、centerY
4.边界:edges
5.偏移量:offset、insets、sizeOffset、centerOffset
6.priority()约束优先级(0~1000)
先实例化三个视图以便于后续操作
UIView *firstView = [[UIView alloc] init];
firstView.backgroundColor = [UIColor orangeColor];
UIView *secondView = [[UIView alloc] init];
secondView.backgroundColor = [UIColor greenColor];
UIView *thirdView = [[UIView alloc] init];
thirdView.backgroundColor = [UIColor blackColor];
[self.view addSubview:secondView];
[self.view addSubview:firstView];
[self.view addSubview:thirdView];
用mas_makeConstraints()
添加约束
[firstView mas_makeConstraints:^(MASConstraintMaker* make) {
//make.left.mas_equalTo(0); //直接在equalTo()内填写数字,默认为相对于父视图而言,等同于下面注释的语句
make.left.mas_equalTo(self.view.mas_left).mas_offset(0);
make.top.mas_equalTo(self.view.mas_top).mas_offset(self.view.frame.size.height * 0.1);
make.width.mas_equalTo(self.view).dividedBy(2);
make.height.mas_equalTo(self.view).dividedBy(5);
}];
[secondView mas_makeConstraints:^(MASConstraintMaker* make) {
make.left.mas_equalTo(self.view.mas_left).mas_offset(0);
make.top.mas_equalTo(self.view.mas_top).mas_offset(self.view.frame.size.height * 0.4);
make.width.mas_equalTo(self.view).dividedBy(2);
make.height.mas_equalTo(self.view).dividedBy(5);
}];
[thirdView mas_makeConstraints:^(MASConstraintMaker* make) {
make.left.mas_equalTo(self.view.mas_left).mas_offset(0);
make.top.mas_equalTo(self.view.mas_top).mas_offset(self.view.frame.size.height * 0.7);
make.width.mas_equalTo(self.view).dividedBy(2);
make.height.mas_equalTo(self.view).dividedBy(5);
}];
效果如下: