Masonry使用

2017-06-20  本文已影响9人  crazyfox

之前的项目一直使用的storyboard+autolayout的方式布局,最近想试下masonry布局

Masonry介绍

Masonry是基于NSLayoutConstraint的再封装,使用链式编程的方式提供API给我们使用,链式编程是使用的责任链模式实现的

Masonry常用API

  • (NSArray *)mas_makeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block;//添加约束

- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedSpacing:(CGFloat)fixedSpacing leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing;
- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedItemLength:(CGFloat)fixedItemLength leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing;

常用函数

equalTo()
greaterThanOrEqualTo()
lessThanOrEqualTo()
and(), with()//没有实际作用
priorityLow()//优先级
multipliedBy//百分比布局
dividedBy//百分比布局

equalTo和mas_equalTo区别

#define mas_equalTo(...) equalTo(MASBoxValue((VA_ARGS)))
/**
*给定一个标量或结构值,将其包装在NSValue中
*基于EXPObjectify:https://github.com/specta/expecta
*/

更新约束和布局

关于更新约束布局相关的API,主要用以下四个API:

  • (void)updateConstraintsIfNeeded 调用此方法,如果有标记为需要重新布局的约束,则立即进行重新布局,内部会调用updateConstraints方法

关于UIView重新布局相关的API,主要用以下三个API:

  • (void)setNeedsLayout 标记为需要重新布局

布局变更

- (void)didTapGrowButton:(UIButton *)button {
if(self.buttonSize.height >= self.frame.size.height)
{
self.buttonSize = CGSizeMake(self.buttonSize.width/1.3, self.buttonSize.height/1.3);
}else{
self.buttonSize = CGSizeMake(self.buttonSize.width * 1.3, self.buttonSize.height * 1.3);
}
// tell constraints they need updating
[self setNeedsUpdateConstraints];
// update constraints now so we can animate the change
[self updateConstraintsIfNeeded];
[UIView animateWithDuration:0.4 animations:^{
[self layoutIfNeeded];
}];
}

上一篇 下一篇

猜你喜欢

热点阅读