前两天看了下Masonry 这个库,感觉灰常不错,虽然只是初步研究了一下,奈何我迫不及待的心情已经促使我,不得不现在就整理上来和小伙伴们一起分享了 ,HOHO........o.o
首先,我们要知道这个库,是封装了NSLayoutAttribute来供我们使用,我喜欢他主要的原因也是因为,调理清晰,适合我这种一根筋,不太聪明,并且只喜欢纯代码的肥胖人士使用。
其次,如果想用这个库,还是要知道什么是约束,约束时应该怎么搭建你的UI的,毕竟他只是让我们更方便的使用AutoLayout,减少项目中的代码量。
更详细的解释都可以百度到,咱们赶紧进入正题上代码喽~:
//
// ViewController.m
// MasonryEex
//
// Created by a111 on 16/4/7.
// Copyright © 2016年 司小文. All rights reserved.
//
#import "ViewController.h"
//需要的类
#import "View+MASAdditions.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//图一效果:
[self makeUI];
//图二效果:
[self makeUIA];
}
#pragma mark 图一效果方法
- (void)makeUI{
//这个方法主要是,需要自动适配的view不确定大小,随着屏幕大小的变化来控制view的大小。
UIView *sv = [[UIView alloc] init];
sv.backgroundColor = [UIColor blackColor];
[self.view addSubview:sv];
[sv mas_makeConstraints:^(MASConstraintMaker *make) {
//设置从顶部到view的约束距离
make.top.offset(50);
//设置从左边界到view的约束距离
make.left.offset(50);
//设置从右边界到view的约束距离
make.right.offset(-50);
//设置从底部到view的约束距离
make.bottom.offset(-50);
}];
UIView *sv2 = [[UIView alloc] init];
sv2.backgroundColor = [UIColor redColor];
[self.view addSubview:sv2];
[sv2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.offset(100);
make.left.offset(100);
make.right.offset(-100);
make.bottom.offset(-100);
}];
UIView *sv3 = [[UIView alloc] init];
sv3.backgroundColor = [UIColor orangeColor];
[self.view addSubview:sv3];
[sv3 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.offset(150);
make.left.offset(150);
make.right.offset(-150);
make.bottom.offset(-150);
}];
}
#pragma mark 图二效果方法
- (void)makeUIA{
//这个方法主要是,一个view,相对于另一个view的边界添加的约束
UIView *sv = [[UIView alloc] init];
sv.backgroundColor = [UIColor blackColor];
[self.view addSubview:sv];
[sv mas_makeConstraints:^(MASConstraintMaker *make) {
//让sv保持在屏幕的中心
make.center.equalTo(self.view);
//设置从左边界到sv的约束距离
make.left.offset((self.view.frame.size.width-100)/2);
//设置从右边界到sv的约束距离
make.right.offset(-(self.view.frame.size.width-100)/2);
//设置sv的高度
make.height.offset(120);
}];
UIView *sv2 = [[UIView alloc] init];
sv2.backgroundColor = [UIColor redColor];
[self.view addSubview:sv2];
[sv2 mas_makeConstraints:^(MASConstraintMaker *make) {
//sv2右边的约束,是根据sv边框的左边边开始算,距离-10
make.right.equalTo(sv.mas_left).offset(-10);
//sv2距离上部的约束,根sv边框的上边一样
make.top.equalTo(sv.mas_top);
//sv2的高度,根sv一样
make.height.equalTo(sv);
//sv2的宽度,根sv一样
make.width.equalTo(sv);
}];
UIView *sv3 = [[UIView alloc] init];
sv3.backgroundColor = [UIColor orangeColor];
[self.view addSubview:sv3];
[sv3 mas_makeConstraints:^(MASConstraintMaker *make) {
//sv3左边边的约束,是根据sv边框的右边边开始算,距离10
make.left.equalTo(sv.mas_right).offset(10);
//sv3距离上部的约束,根sv边框的上边一样
make.top.equalTo(sv.mas_top);
//sv3的高度,根sv一样
make.height.equalTo(sv);
//sv3的宽度,根sv一样
make.width.equalTo(sv);
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
效果图如下:
图一:
图二:
demo地址:
https://yunpan.cn/cqvRGGHTctpMB (提取码:bf17)
感谢观看,学以致用更感谢~~