iOS Masonry的使用需要注意的地方
自動布局最重要的是約束
:UI元素間關系的數(shù)學表達式虎忌。約束包括尺寸访惜、由優(yōu)先級和閾值管理的相對位置。它們是添加劑萍虽,可能導致約束沖突
、約束不足造成布局無法確定 形真。這兩種情況都會產生異常杉编。
使用前:AutoLayout關于更新的幾個方法的區(qū)別
setNeedsLayout
:告知頁面需要更新,但是不會立刻開始更新咆霜。執(zhí)行后會立刻調用layoutSubviews邓馒。
layoutIfNeeded
:告知頁面布局立刻更新。所以一般都會和setNeedsLayout一起使用蛾坯。如果希望立刻生成新的frame需要調用此方法光酣,利用這點一般布局動畫可以在更新布局后直接使用這個方法讓動畫生效。
layoutSubviews
:系統(tǒng)重寫布局
setNeedsUpdateConstraints
:告知需要更新約束脉课,但是不會立刻開始
updateConstraintsIfNeeded
:告知立刻更新約束
updateConstraints
:系統(tǒng)更新約束
使用
- 基本使用
mas_makeConstraints
:添加約束
mas_updateConstraints
:更新約束救军、亦可添加新約束
mas_remakeConstraints
:重置之前的約束
multipler
屬性表示約束值為約束對象的乘因數(shù),
dividedBy
屬性表示約束值為約束對象的除因數(shù)财异,可用于設置view
的寬高比
//
進行屏幕的適配的時候,往往需要根據(jù)屏幕寬度來適配一個相應的高度唱遭,在此推薦使用如下約束的方式來進行控件的適配
[self.topView
addSubview:self.topInnerView];
[self.topInnerView mas_makeConstraints:^(MASConstraintMaker *make)
{
make.height.equalTo(self.topView.mas_height).dividedBy(3);
make.width.and.height.lessThanOrEqualTo(self.topView);
make.width.and.height.equalTo(self.topView).with.priorityLow();
make.center.equalTo(self.topView);
}];
priorityLow()
設置約束優(yōu)先級
define
MAS_SHORTHAND_GLOBALS
使用全局宏定義戳寸,可以使equalTo
等效于mas_equalTo
define MAS_SHORTHAND
使用全局宏定義,
可以在調用masonry方法的時候不使用mas_
前綴
// 這里注意到一個地方,就是當使用了這個全局宏定義之后胆萧,發(fā)現(xiàn)可以有個類NSArray+MASAdditions.h
庆揩,看了之后發(fā)現(xiàn)可以
self.buttonViews = @[ raiseButton, lowerButton, centerButton ];
// 之后可以在updateConstraints 方法中
- (void)updateConstraints {
[self.buttonViews updateConstraints:^(MASConstraintMaker *make) {
make.baseline.equalTo(self.mas_centerY).with.offset(self.offset);
}];
[super updateConstraints];
}
動態(tài)修改視圖約束:
// 創(chuàng)建視圖約束
[blueView mas_makeConstraints:^(MASConstraintMaker *make) {
self.animatableConstraint = make.edges.equalTo(superview).insets(paddingInsets).priorityLow();
]];
// 更改約束 (另一處方法中)
UIEdgeInsets paddingInsets = UIEdgeInsetsMake(padding, padding, padding, padding);
self.animatableConstraint.insets = paddingInsets;
[self layoutIfNeeded];
debug
模式:
// 對某個view添加key值
greenView.mas_key = @"greenView";
// 或者如下順序
MASAttachKeys(greenView, redView, blueView, superview);
// 同樣的對每條約束亦可以添加key
make.height.greaterThanOrEqualTo(@5000).key(@"ConstantConstraint");
preferredMaxLayoutWidth
:
多行l(wèi)abel的約束問題
// 已經確認好了位置
// 在layoutSubviews中確認label的preferredMaxLayoutWidth值
- (void)layoutSubviews {
[super layoutSubviews];
// 你必須在 [super layoutSubviews] 調用之后跌穗,longLabel的frame有值之后設置preferredMaxLayoutWidth
self.longLabel.preferredMaxLayoutWidth = self.frame.size.width-100;
// 設置preferredLayoutWidth后订晌,需要重新布局
[super layoutSubviews];
}
scrollView
使用約束的問題:原理通過一個contentView來約束scrollView的contentSize大小,也就是說以子控件的約束條件蚌吸,來控制父視圖的大小
// 1. 控制scrollView大行獠Α(顯示區(qū)域)
[self.scrollView makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view);
}];
// 2. 添加一個contentView到scrollView,并且添加好約束條件
[contentView makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.scrollView);
// 注意到此處的寬度約束條件羹唠,這個寬度的約束條件是比添加項
make.width.equalTo(self.scrollView);
}];
// 3. 對contentView的子控件做好約束奕枢,達到可以控制contentView的大小
新方法:2個或2個以上的控件等間隔排序
/**
- 多個控件固定間隔的等間隔排列,變化的是控件的長度或者寬度值
- @param axisType 軸線方向
- @param fixedSpacing 間隔大小
- @param leadSpacing 頭部間隔
- @param tailSpacing 尾部間隔
*/
- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType
withFixedSpacing:(CGFloat)fixedSpacing l
eadSpacing:(CGFloat)leadSpacing
tailSpacing:(CGFloat)tailSpacing;
/**
- 多個固定大小的控件的等間隔排列,變化的是間隔的空隙
- @param axisType 軸線方向
- @param fixedItemLength 每個控件的固定長度或者寬度值
- @param leadSpacing 頭部間隔
- @param tailSpacing 尾部間隔
*/
- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType
withFixedItemLength:(CGFloat)fixedItemLength
leadSpacing:(CGFloat)leadSpacing
tailSpacing:(CGFloat)tailSpacing;
使用方法很簡單佩微,因為它是NSArray的類擴展:
// 創(chuàng)建水平排列圖標 arr中放置了2個或連個以上的初始化后的控件
// alongAxis 軸線方向 固定間隔 頭部間隔 尾部間隔
[arr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:20 leadSpacing:5 tailSpacing:5];
[arr makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(@60);
make.height.equalTo(@60);
}];
- 注意事項
約束視圖對象只有在被addSubview
之后缝彬,才能給視圖添加約束
當你的所有約束都在updateConstraints
內調用的時候,你就需要在此調用此方法哺眯,因為updateConstraints
方法是需要觸發(fā)的
// 調用在view 內部谷浅,而不是viewcontroller
- (BOOL)requiresConstraintBasedLayout {
return YES;
}
/**
- 蘋果推薦 約束 增加和修改 放在此方法種
*/
- (void)updateConstraints {
[self.growingButton updateConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self);
make.width.equalTo(@(self.buttonSize.width)).priorityLow();
make.height.equalTo(@(self.buttonSize.height)).priorityLow();
make.width.lessThanOrEqualTo(self);
make.height.lessThanOrEqualTo(self);
}];
//最后記得回調super方法
[super updateConstraints];
}
如果想要約束變換之后實現(xiàn)動畫效果,則需要執(zhí)行如下操作
// 通知需要更新約束奶卓,但是不立即執(zhí)行
[self setNeedsUpdateConstraints];
// 立即更新約束一疯,以執(zhí)行動態(tài)變換
// update constraints now so we can animate the change
[self updateConstraintsIfNeeded];
// 執(zhí)行動畫效果, 設置動畫時間
[UIView animateWithDuration:0.4 animations:^{
[self layoutIfNeeded];
}];
自動計算UITableViewCell高度
推薦使用一個庫[UITableView-FDTemplateLayoutCell
想法:動態(tài)高度的cell, 主要關注的點是什么?
viewController本身不需要知道cell的類型
cell的高度與viewController沒有相關性夺姑,cell的高度由cell本身來決定
viewController真正做到的是一個
以下是摘抄過來的
主要是UILabel的高度會有變化墩邀,所以這里主要是說說label變化時如何處理,設置UILabel的時候注意要設置
preferredMaxLayoutWidth這個寬度盏浙,還有ContentHuggingPriority為
UILayoutPriorityRequried
CGFloat maxWidth = [UIScreen mainScreen].bounds.size.width - 10 * 2;
textLabel = [UILabel new];
textLabel.numberOfLines = 0;
textLabel.preferredMaxLayoutWidth = maxWidth;
[self.contentView addSubview:textLabel];
[textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(statusView.mas_bottom).with.offset(10);
make.left.equalTo(self.contentView).with.offset(10);
make.right.equalTo(self.contentView).with.offset(-10);
make.bottom.equalTo(self.contentView).with.offset(-10);
}];
[_contentLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
如果版本支持最低版本為iOS
8以上的話可以直接利用UITableViewAutomaticDimension在tableview的heightForRowAtIndexPath直接返回即可眉睹。
tableView.rowHeight = UITableViewAutomaticDimension;
tableView.estimatedRowHeight = 80; //減少第一次計算量,iOS7后支持
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// 只用返回這個废膘!
return UITableViewAutomaticDimension;
}
但如果需要兼容iOS
8之前版本的話竹海,就要回到老路子上了,主要是用systemLayoutSizeFittingSize來取高殖卑。步驟是先在數(shù)據(jù)model中添加一個
height的屬性用來緩存高,然后在table
view的heightForRowAtIndexPath代理里static一個只初始化一次的Cell實例坊萝,然后根據(jù)model內容填充數(shù)據(jù)孵稽,最后根
據(jù)cell的contentView的systemLayoutSizeFittingSize的方法獲取到cell的高许起。具體代碼如下
//在model中添加屬性緩存高度
@interface DataModel : NSObject
@property (copy, nonatomic) NSString *text;
@property (assign, nonatomic) CGFloat cellHeight; //緩存高度
@end
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
static CustomCell *cell;
//只初始化一次cell
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CustomCell class])];
});
DataModel *model = self.dataArray[(NSUInteger) indexPath.row];
[cell makeupData:model];
if (model.cellHeight <= 0) {
//使用systemLayoutSizeFittingSize獲取高度
model.cellHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height + 1;
}
return model.cellHeight;
}