之前的項(xiàng)目一直使用的storyboard+autolayout的方式布局,最近想試下masonry布局
Masonry介紹
Masonry是基于NSLayoutConstraint的再封裝,使用鏈?zhǔn)骄幊痰姆绞教峁〢PI給我們使用,鏈?zhǔn)骄幊淌鞘褂玫呢?zé)任鏈模式實(shí)現(xiàn)的
Masonry常用API
- (NSArray *)mas_makeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block;//添加約束
- (NSArray *)mas_updateConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block;//移除之前的約束鹃愤,重新添加約束
- (NSArray *)mas_remakeConstraints:(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;
常用函數(shù)
equalTo()
greaterThanOrEqualTo()
lessThanOrEqualTo()
and(), with()//沒(méi)有實(shí)際作用
priorityLow()//優(yōu)先級(jí)
multipliedBy//百分比布局
dividedBy//百分比布局
equalTo和mas_equalTo區(qū)別
#define mas_equalTo(...) equalTo(MASBoxValue((VA_ARGS)))
/**
*給定一個(gè)標(biāo)量或結(jié)構(gòu)值机久,將其包裝在NSValue中
*基于EXPObjectify:https://github.com/specta/expecta
*/
更新約束和布局
關(guān)于更新約束布局相關(guān)的API凡泣,主要用以下四個(gè)API:
- (void)updateConstraintsIfNeeded 調(diào)用此方法,如果有標(biāo)記為需要重新布局的約束轨帜,則立即進(jìn)行重新布局魄咕,內(nèi)部會(huì)調(diào)用updateConstraints方法
- (void)updateConstraints 重寫此方法,內(nèi)部實(shí)現(xiàn)自定義布局過(guò)程
- (BOOL)needsUpdateConstraints 當(dāng)前是否需要重新布局蚌父,內(nèi)部會(huì)判斷當(dāng)前有沒(méi)有被標(biāo)記的約束
- (void)setNeedsUpdateConstraints 標(biāo)記需要進(jìn)行重新布局
關(guān)于UIView重新布局相關(guān)的API哮兰,主要用以下三個(gè)API:
- (void)setNeedsLayout 標(biāo)記為需要重新布局
- (void)layoutIfNeeded 查看當(dāng)前視圖是否被標(biāo)記需要重新布局,有則在內(nèi)部調(diào)用layoutSubviews方法進(jìn)行重新布局
- (void)layoutSubviews 重寫當(dāng)前方法苟弛,在內(nèi)部完成重新布局操作
布局變更
- (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];
}];
}