Masonry之AutoLayout与Masonry基本使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_18683985/article/details/87938507

1.复习一下AutoLayout的用法

这里我们只复习一下和Masonry相关部分的用法,字符串的那个就忽略了.

	// 1. 首先创建collectionView
	self.collectionView = xxxxxxx;
	// 2.父视图添加子视图
	[self addSubView:self.collectionView];
	// 3.设置自动布局
	self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
	// 4.添加约束
    [self addConstraints:@[
                                          [NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1 constant:0],
                                          [NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1 constant:0],
                                          [NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:1 constant:0]
                                          ,[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1 constant:0]
                                          ]];

首先,这里约束是添加在父视图上头滴.我们将一根约束单独抽出来看看

1.withItem:需要添加约束的子视图
2.withItem's attribute:子视图本身的位置.我们这里传入的是left.也就是坐标.
3.withItem's relatedBy:关系(大于等于,小于等于,等于三种).我们这里传入的是等于.
4.toItem:子视图相当于谁布局
5.toItem's attribute:toItem的参照位置.这里我们传入的是左边
6.toItem's multiplier:比例大小,当传入高度等的时候可以传入0.5这种参数.(Mas这玩意默认就是1.注意是CGFloat类型的,传入0会崩溃)
7.toItem's constant:距离多少.类似于Masonry里头的offset()/equto(@());比如我们如果这里传入一个2的话,就是withItem的左边距离toItem左边的5.

[NSLayoutConstraint constraintWithItem:self.collectionView 
attribute:NSLayoutAttributeLeft 
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeLeft
multiplier:1
constant:0
]

这么一坨代码放到Masonry里头就简单了.

	// 1. 首先创建collectionView
	self.collectionView = xxxxxxx;
	// 2.父视图添加子视图
	[self addSubView:self.collectionView];
	// 3.添加约束
	self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
		make.left.offset(0);
		make.top.offset(0);
		make.right.offset(0);
		make.bottom.offset(0);
	}];
	或者中间的block简写为
	make.edges.offset(0);

猜你喜欢

转载自blog.csdn.net/qq_18683985/article/details/87938507