AutoLayout框架Masonry使用心得
我們組分享會上分享了頁面布局的一些寫法,中途提到了AutoLayout,會后我決定將很久前挖的一個坑給填起來(還有好多坑就不說了,說了不填更毀形象了)。
可使用的框架首推Masonry,關于為啥選擇Masonry看看官方文檔就明白了https://github.com/SnapKit/Masonry,官方稱AutoLayout所有功能Masonry都支持。這次項目界面方面我就全部使用了Masonry。
AutoLayout的一些基本概念
- 利用約束來控制視圖的大小和位置,系統會在運行時通過設置的約束計算得到frame再繪制屏幕
- 兩個屬性Content Compression Resistance(排擠,值越高越固定)和Content Hugging(擁抱),Masonry代碼如下 </ul>
//content hugging 為1000 [view setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];//content compression 為250 [view setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];</pre>
- multipler屬性表示約束值為約束對象的百分比,在Masonry里有對應的multipliedBy函數 </ul>
//寬度為superView寬度的20% make.width.equalTo(superView.mas_width).multipliedBy(0.2);
- AutoLayout下UILabel設置多行計算需要設置preferredMaxLayoutWidth </ul>
label.preferredMaxWidth = [UIScreen mainScreen].bounds.size.width - margin - padding;
- preferredMaxLayoutWidth用來制定最大的寬,一般用在多行的UILabel中
- systemLayoutSizeFittingSize方法能夠獲得view的高度
- iOS7有兩個很有用的屬性,topLayoutGuide和bottomLayoutGuide,這個兩個主要是方便獲取UINavigationController和UITabBarController的頭部視圖區域和底部視圖區域。 </ul>
//Masonry直接支持這個屬性 make.top.equalTo(self.mas_topLayoutGuide);
AutoLayout關于更新的幾個方法的區別
- setNeedsLayout:告知頁面需要更新,但是不會立刻開始更新。執行后會立刻調用layoutSubviews。
- layoutIfNeeded:告知頁面布局立刻更新。所以一般都會和setNeedsLayout一起使用。如果希望立刻生成新的frame需要調用此方法,利用這點一般布局動畫可以在更新布局后直接使用這個方法讓動畫生效。
- layoutSubviews:系統重寫布局
- setNeedsUpdateConstraints:告知需要更新約束,但是不會立刻開始
- updateConstraintsIfNeeded:告知立刻更新約束
- updateConstraints:系統更新約束 </ul>
- 用mas_makeConstraints的那個view需要在addSubview之后才能用這個方法
- mas_equalTo適用數值元素,equalTo適合多屬性的比如make.left.and.right.equalTo(self.view)
- 方法and和with只是為了可讀性,返回自身,比如make.left.and.right.equalTo(self.view)和make.left.right.equalTo(self.view)是一樣的。
- 因為iOS中原點在左上角所以注意使用offset時注意right和bottom用負數。 </ul>
Masonry使用注意事項
Masonry適配iOS6和iOS7時需要注意的問題
開發項目時是先在iOS8上調試完成的,測試時發現低版本的系統會發生奔潰的現象,修復后總結問題主要是在equalTo的對象指到了父視圖的父視圖或者父視圖同級的子視圖上造成的,所以做約束時如果出現了奔潰問題百分之九十都是因為這個。
Masonry使用范例
基本寫法
//相對于父視圖邊距為10 UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10); [self.avatarView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(superview.mas_top).with.offset(padding.top); //with is an optional semantic filler make.left.equalTo(superview.mas_left).with.offset(padding.left); make.bottom.equalTo(superview.mas_bottom).with.offset(-padding.bottom); make.right.equalTo(superview.mas_right).with.offset(-padding.right); }];//相對于父視圖邊距為10簡潔寫法 [self.avatarView mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.equalTo(superview).with.insets(padding); }];
//這兩個作用完全一樣 [self.avatarView mas_makeConstraints:^(MASConstraintMaker *make) { make.left.greaterThanOrEqualTo(self.view); make.left.greaterThanOrEqualTo(self.view.mas_left); }];
//.equalTo .lessThanOrEqualTo .greaterThanOrEqualTo使用NSNumber [self.avatarView mas_makeConstraints:^(MASConstraintMaker *make) { make.width.greaterThanOrEqualTo(@200); make.width.lessThanOrEqualTo(@400); make.left.lessThanOrEqualTo(@10); }];
//如果不用NSNumber可以用以前的數據結構,只需用mas_equalTo就行 [self.avatarView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(42); make.height.mas_equalTo(20); make.size.mas_equalTo(CGSizeMake(50, 100)); make.edges.mas_equalTo(UIEdgeInsetsMake(10, 0, 10, 0)); make.left.mas_equalTo(self.view).mas_offset(UIEdgeInsetsMake(10, 0, 10, 0)); }];
//也可以使用數組 [self.avatarView mas_makeConstraints:^(MASConstraintMaker *make) { make.height.equalTo(@[self.view.mas_height, superview.mas_height]); make.height.equalTo(@[self.view, superview]); make.left.equalTo(@[self.view, @100, superview.mas_right]); }];
// priority的使用 [self.avatarView mas_makeConstraints:^(MASConstraintMaker *make) { make.left.greaterThanOrEqualTo(self.view.mas_left).with.priorityLow(); make.top.equalTo(self.view.mas_top).with.priority(600); }];
//同時創建多個約束 [self.avatarView mas_makeConstraints:^(MASConstraintMaker *make) { //讓top,left,bottom,right都和self.view一樣 make.edges.equalTo(self.view); //edges make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(5, 10, 15, 20)); //size make.size.greaterThanOrEqualTo(self.view); make.size.equalTo(superview).sizeOffset(CGSizeMake(100, -50)); //center make.center.equalTo(self.view); make.center.equalTo(self.view).centerOffset(CGPointMake(-5, 10)); //chain make.left.right.and.bottom.equalTo(self.view); make.top.equalTo(self.view); }];</pre>
AutoLayout情況如何計算UITableView的變高高度
主要是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];</pre>
如果版本支持最低版本為iOS 8以上的話可以直接利用UITableViewAutomaticDimension在tableview的heightForRowAtIndexPath直接返回即可。
tableView.rowHeight = UITableViewAutomaticDimension; tableView.estimatedRowHeight = 80; //減少第一次計算量,iOS7后支持
(CGFloat)tableView:(UITableView )tableView heightForRowAtIndexPath:(NSIndexPath )indexPath { // 只用返回這個! return UITableViewAutomaticDimension; }</pre>
但如果需要兼容iOS 8之前版本的話,就要回到老路子上了,主要是用systemLayoutSizeFittingSize來取高。步驟是先在數據model中添加一個height的屬性用來緩存高,然后在table view的heightForRowAtIndexPath代理里static一個只初始化一次的Cell實例,然后根據model內容填充數據,最后根據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; }</pre>
動畫
因為布局約束就是要脫離frame這種表達方式的,可是動畫是需要根據這個來執行,這里面就會有些矛盾,不過根據前面說到的布局約束的原理,在某個時刻約束也是會被還原成frame使視圖顯示,這個時刻可以通過layoutIfNeeded這個方法來進行控制。具體代碼如下
[aniView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.bottom.left.right.equalTo(self.view).offset(10); }];
[aniView mas_updateConstraints:^(MASConstraintMaker *make) { make.top.equalTo(self.view).offset(30); }];
[UIView animateWithDuration:3 animations:^{ [self.view layoutIfNeeded]; }];</pre>
參考文章
- Masonry官網:https://github.com/SnapKit/Masonry
- Apple官方Auto Layout Guide:https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/Introduction/Introduction.html
- WWDC2012 session 202 – Introduction to Auto Layout for iOS and OS X: https://developer.apple.com/videos/wwdc/2012/?id=202
- WWDC2012 session 228 – Best Practices for Mastering Auto Layout:https://developer.apple.com/videos/wwdc/2012/?id=228
- WWDC2012 session 232 – Auto Layout by Example:https://developer.apple.com/videos/wwdc/2012/?id=232 </ul>