您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

Auto Layout 深入講解:壓縮阻力與內容吸附

編輯:iOS 開發基礎

本文為投稿文章,作者:梁煒V

使用 Auto Layout 時,有兩個極其重要的布局概念:Content Compression Resistance 與 Content Hugging,字面可分別譯為「壓縮阻力」與「內容吸附」。僅憑字面很難理解它們的用法與設計意圖。我起初也頗感困惑,日常開發中幾乎沒用過它們,直到近來稍作研究,才發現其作用之大,於是趁機整理記錄,加深印象。

注:下文為表述方便,將 Content Compression Resistance 記為「壓縮阻力」,Content Hugging 記為「內容吸附」。

Content Compression Resistance

「壓縮阻力」可以形象地理解為「離我遠點,別擠到我」。它的優先級越高,抗擠壓能力就越強。我們可以通過代碼在水平或垂直方向上設置 1(最低)到 1000(最高)的優先級,默認為 750。例如為一個 UILabel 設置水平方向優先級為 500 的壓縮阻力:

[label setContentCompressionResistancePriority:500 forAxis:UILayoutConstraintAxisHorizontal];

用圖表示大致如下:壓縮阻力就像視圖自身向外的張力,優先級越高,維持自身完整顯示的能力就越強:

Content Hugging

「內容吸附」可理解為「抱緊(Hug)」:視圖不會隨父視圖變大而拉伸,只維持能完整容納自身內容的大小。優先級越高,這種吸附能力越強。它同樣可通過代碼設置,只是默認優先級為 250:

[label setContentHuggingPriority:251 forAxis:UILayoutConstraintAxisHorizontal];

用圖表示大致如下:內容吸附就像視圖自身向內抱緊的力量,優先級越高能力越強:

以上兩個屬性都建立在 Intrinsic Content Size(固有尺寸)這一概念之上。所有基於 UIView 的視圖都有 intrinsicContentSize 屬性,下面介紹什麼是固有尺寸。

Intrinsic Content Size

每個視圖都有壓縮阻力與內容吸附優先級,但只有在視圖明確了固有尺寸後,這兩種優先級才會生效。先看官方解釋:

Custom views typically have content that they display of which the layout system is unaware. Overriding this method allows a custom view to communicate to the layout system what size it would like to be based on its content. This intrinsic size must be independent of the content frame, because there’s no way to dynamically communicate a changed width to the layout system based on a changed height, for example.

If a custom view has no intrinsic size for a given dimension, it can return UIViewNoIntrinsicMetric for that dimension.

大意思是:自定義視圖默認情況下固有尺寸返回 (UIViewNoIntrinsicMetric, UIViewNoIntrinsicMetric),即 (-1, -1);只有根據自身 Content 重寫該方法,自定義視圖才能讓布局系統明確其應展示的大小。UILabel、UIButton 等控件,系統默認已根據內容實現了固有尺寸,因此使用時只需確定 origin 或 Center 就能正確顯示。可見,固有尺寸是為實現視圖「大小自適應」而存在的。

下面我自定義一個視圖來驗證固有尺寸是否有效。由於項目中普遍用 Masonry 處理 Auto Layout,以下示例均使用 Masonry 布局。

重寫 Intrinsic Content Size

新建一個繼承自 UIView 的自定義視圖 IntrinsicView,在 ViewController 中添加它,設置水平居中、頂部與父視圖對齊。

- (void)layoutSubIntrinsicView { IntrinsicView *intrinsicView = [IntrinsicView new]; intrinsicView.backgroundColor = [UIColor colorWithRed:.2 green:.4 blue:.6 alpha:1]; [self.view addSubview:intrinsicView]; [intrinsicView mas_makeConstraints:^(MASConstraintMaker *make) { make.centerX.mas_equalTo(self.view); make.top.mas_equalTo(self.mas_topLayoutGuideBottom); }]; }

運行後發現什麼也沒顯示,因為我們沒設寬高,而它默認固有尺寸為 (-1, -1)。重寫 IntrinsicView 的 intrinsicContentSize 方法:

@implementation IntrinsicView - (CGSize)intrinsicContentSize { return CGSizeMake(150, 66); } @end

運行後顯示如下:

1、測試內容吸附優先級

為測試內容吸附,在頁面上添加兩個 IntrinsicView:topView 與 bottomView,均水平居中,分別與頁面頂部、底部對齊:

- (void)layoutSubIntrinsicView { IntrinsicView *topView = [IntrinsicView new]; topView.backgroundColor = [UIColor colorWithRed:.2 green:.4 blue:.6 alpha:1]; [self.view addSubview:topView]; [topView mas_makeConstraints:^(MASConstraintMaker *make) { make.centerX.mas_equalTo(self.view); make.top.mas_equalTo(self.mas_topLayoutGuideBottom); }]; IntrinsicView *bottomView = [IntrinsicView new]; bottomView.backgroundColor = [UIColor colorWithRed:.2 green:.4 blue:.6 alpha:1]; [self.view addSubview:bottomView]; [bottomView mas_makeConstraints:^(MASConstraintMaker *make) { make.centerX.mas_equalTo(self.view); make.bottom.mas_equalTo(self.mas_bottomLayoutGuideBottom); }]; }

運行後如下:

下面設置 topView 與 bottomView 間距為 40,即 topView.bottom + 40 = bottomView.top:

[bottomView mas_makeConstraints:^(MASConstraintMaker *make) { make.centerX.mas_equalTo(self.view); make.top.mas_equalTo(topView.mas_bottom).offset(40); make.bottom.mas_equalTo(self.mas_bottomLayoutGuideBottom); }];

運行後:

可以發現 topView 被拉伸了。若不希望它被拉伸,就可利用內容吸附的特性:因為已定義 IntrinsicView 的固有尺寸,只要把 topView 的內容吸附優先級設得比 bottomView 高即可。默認是 250,我們把 topView 設為 251,在 layoutSubIntrinsicView 末尾添加:

[topView setContentHuggingPriority:251 forAxis:UILayoutConstraintAxisVertical];

運行後如下,達到了預期效果:

(251 只是隨意取的大於 250 的值,也可以是 250 到 1000 之間的任何值。)

2、測試壓縮阻力優先級

我們常遇到這樣的需求:

在某頁面上水平放置兩個 UILabel:leftLabel 左邊與父視圖間距固定,rightLabel 右邊與父視圖間距小於等於某值,兩者間距固定,寬度各自根據內容自適應。關鍵代碼如下:

[leftLabel mas_makeConstraints:^(MASConstraintMaker *make) { make.left.mas_equalTo(self.view).offset(10); make.top.mas_equalTo(80); }]; [rightLabel mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(leftLabel); make.left.mas_equalTo(leftLabel.mas_right).offset(20); make.right.mas_lessThanOrEqualTo(self.view).offset(-10); }];

在內容寬度不超過父視圖時,兩個 label 都能完整顯示;但當總寬超出父視圖時,就會出現:

其中一個 label 被壓縮,rightLabel 顯示不全。若此時希望 leftLabel 被壓縮、rightLabel 盡量完整顯示,可利用壓縮阻力的特性,把 rightLabel 的壓縮阻力優先級設得比 leftLabel 高。默認為 750,我們把 rightLabel 設為 751,在上面代碼末尾添加:

[rightLabel setContentCompressionResistancePriority:751 forAxis:UILayoutConstraintAxisHorizontal];

運行後如下,達到了預期效果:

3、在自動計算 UITableViewCell 高度中的使用

過去處理變高 cell,我們都在 heightForRowAtIndexPath 裡手動拼湊高度;一旦調整 cell 內控件布局或新增控件,還得同步修改計算方法,非常不便。有了自動布局後,善用壓縮阻力與內容吸附的優先級,就能讓系統精確而簡單地算出變高 cell 的高度。

假定需求如下:

這個變高 cell 中高度不定的是中間的 ContentLabel,它會依內容長度折行顯示。UILabel 要折行,需設置 preferredMaxLayoutWidth 與 numberOfLines。先假定 Model 定義如下:

@interface CellModel : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *company; @property (nonatomic, copy) NSString *content; @property (nonatomic, assign) CGFloat cacheHeight;// 緩存當前 Model 的 cell 高度 @end

自定義 UITableViewCell 的關鍵代碼如下:

// 圖片距左邊 10,上下居中 [_cellImageView mas_makeConstraints:^(MASConstraintMaker *make) { make.left.mas_equalTo(self.contentView).offset(10); make.centerY.mas_equalTo(self.contentView); make.top.mas_greaterThanOrEqualTo(self.contentView).offset(10); make.bottom.mas_lessThanOrEqualTo(self.contentView).offset(-10); }]; // 標題 Label,一行顯示 [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) { make.left.mas_equalTo(self.cellImageView.mas_right).offset(6); make.right.mas_lessThanOrEqualTo(self.contentView).offset(-10); make.top.mas_equalTo(self.contentView).offset(10); }]; // 內容 Label,多行顯示 _contentLabel.numberOfLines = 0; [self.contentView addSubview:_contentLabel]; [_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) { make.left.mas_equalTo(self.nameLabel); make.top.mas_equalTo(self.nameLabel.mas_bottom).offset(6); }]; // 公司 Label,一行顯示 [_companyLabel mas_makeConstraints:^(MASConstraintMaker *make) { make.left.mas_equalTo(self.contentLabel); make.right.mas_lessThanOrEqualTo(self.contentView).offset(-10); make.top.mas_equalTo(self.contentLabel.mas_bottom).offset(6); make.bottom.mas_equalTo(self.contentView).offset(-10); }]; [_nameLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical]; [_companyLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical]; [_contentLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];

這裡把幾個 UILabel 的內容吸附優先級設為最高,使其不會隨 cell 高度變化而拉伸。contentLabel 設了 numberOfLines = 0,還需設置 preferredMaxLayoutWidth 才能正確換行。由於 cell 顯示前不知寬度,可在 layoutSubviews 中設置:

- (void)layoutSubviews { _contentLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.contentView.frame) - 128 - 10 - 6; [super layoutSubviews]; }

設置好 cell 與 Model 後,其餘用法與普通情況一致,唯一不同在於計算高度的 heightForRowAtIndexPath,實現如下:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { static CodeLayoutCell *singleCell = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ singleCell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier]; }); CellModel *model = _dataSourceArray[indexPath.row]; if (model.cacheHeight != 0) { return model.cacheHeight; } [singleCell layoutIfNeeded]; [singleCell setNewCellModel:model]; CGSize size = [singleCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; model.cacheHeight = size.height + 1; return model.cacheHeight; }

運行效果如下:

當圖片高度大於三個 UILabel 加上各自間距的總高度時,由於我們把三個 Label 的內容吸附設為最高,為滿足它們的高度,圖片內容就被壓縮了:

第二個 cell 的圖片被壓縮了,如何保證它不被壓縮呢?就留給讀到這裡的你自行實現吧!由於剛接觸這兩個屬性,難免有疏漏之處,敬請諒解。完整 demo 請戳原文鏈接。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved