UITableViewCell使用自動布局的“最佳實(shí)踐”

前言

iOS 處理TableView的復(fù)雜Cell是一件很麻煩的事情,我們得計算Cell里面內(nèi)容的Frame以及Cell的高度,現(xiàn)在有一種相對高效的方式握巢,使用自動布局的Cell可以讓這件事變得容易起來了,不用再去計算里面的Frame和自身的高度,接下來談?wù)撓逻@種方式的實(shí)現(xiàn)以及里面的坑剩辟。

實(shí)戰(zhàn)

我們實(shí)現(xiàn)了一個這樣的UITableView:

自動布局Cell的TableView
自動布局Cell的TableView

這是一個簡單的列表,和其他的列表無異,不過Cell里面的布局使用了是自動布局贩猎。

  • 首先需要設(shè)置UITableVIew的自動布局相關(guān)的屬性
    self.tableView.estimatedRowHeight = 200;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
  • 然后重寫UITableVIew的delegate和DataSource方法

這里不需要再重寫返回cell高度的方法了熊户,因?yàn)槭褂昧俗詣硬季值腃ell,Cell的高度有Cell的內(nèi)容來決定就好了吭服。

#pragma mark - ......::::::: UITableViewDelegate :::::::......

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AutolayoutCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AutolayoutCell class])];
    GameModel* gameModel = _datas[indexPath.row];
    [cell loadData:gameModel indexPath:indexPath];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    [TagViewUtils showTaggingViewWithView:cell.contentView];
}
  • 接下來就是Cell的實(shí)現(xiàn)了

自動布局的框架使用的是Masonry嚷堡,自動布局的Cell基本的思想就是讓Cell里面的內(nèi)容決定Cell的高度,所以除了常規(guī)的設(shè)置元素的約束之外艇棕,還需要一個到父View底部的約束蝌戒,這樣父View才會根據(jù)子View的內(nèi)容計算出自身的高度。特別地欠肾,需要給最后設(shè)置的這個約束添加上一個優(yōu)先級的值瓶颠,可以設(shè)置為是一個小于1000的值,這里設(shè)置的是900刺桃,因?yàn)閕OS計算高度會有點(diǎn)小的偏差粹淋,是一個很小的小數(shù)值,在運(yùn)行的時候會出現(xiàn)類似的警告信息:

2017-05-28 00:04:31.751783+0800 AutolayoutCell[27341:18908463] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<MASLayoutConstraint:0x6000000b7c40 UIImageView:0x7ff9afd1a1f0.top == UITableViewCellContentView:0x7ff9afd199b0.top + 9.03333>",
    "<MASLayoutConstraint:0x6000000b7d00 UIImageView:0x7ff9afd1a1f0.bottom == UITableViewCellContentView:0x7ff9afd199b0.bottom - 9>",
    "<MASLayoutConstraint:0x6000000b7ee0 UIImageView:0x7ff9afd1a1f0.height == 61>",
    "<NSLayoutConstraint:0x618000091a80 UITableViewCellContentView:0x7ff9afd199b0.height == 79>"
)

Will attempt to recover by breaking constraint 
<MASLayoutConstraint:0x6000000b7ee0 UIImageView:0x7ff9afd1a1f0.height == 61>

可以通過設(shè)置最終決定父View高度的子View到父View底部的約束的優(yōu)先級來解決這個問題瑟慈。

    [gameIconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(84.0/3);
        make.top.equalTo(self.contentView).offset(27.1/3);
        make.bottom.equalTo(self.contentView).offset(-27.1/3);
        make.width.equalTo(@(183.0/3));
        // 設(shè)置優(yōu)先級處理警告信息
        make.height.equalTo(@(183.0/3)).priority(900);
    }];

完整的Cell代碼實(shí)現(xiàn)


#import "AutolayoutCell.h"
#import <Masonry.h>
#import "GameModel.h"
#import <UIImageView+WebCache.h>

@interface AutolayoutCell () {
    GameModel* _gameModel;
}

@property (nonatomic, weak) UIImageView* gameIconImageView;
@property (nonatomic, weak) UILabel* gameTitleLabel;
@property (nonatomic, weak) UILabel* gameTagLabel;
@property (nonatomic, weak) UILabel* gameRateLabel;

@end

@implementation AutolayoutCell

- (instancetype)init {
    self = [super init];
    if (self) {
        [self myInit];
    }
    return self;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self myInit];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

- (void)myInit {
    UIImageView* gameIconImageView = [UIImageView new];
    gameIconImageView.backgroundColor = [UIColor redColor];
    gameIconImageView.contentMode = UIViewContentModeScaleAspectFill;
    gameIconImageView.layer.cornerRadius = 5;
    gameIconImageView.layer.masksToBounds = YES;
    [self.contentView addSubview:gameIconImageView];
    [gameIconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(84.1/3);
        make.top.equalTo(self.contentView).offset(27.1/3);
        make.bottom.equalTo(self.contentView).offset(-27.0/3);
        make.width.equalTo(@(183.0/3));
        make.height.equalTo(@(183.0/3)).priority(900);
    }];
    _gameIconImageView = gameIconImageView;
    
    
    UILabel* gameRateLabel = [UILabel new];
    gameRateLabel.numberOfLines = 1;
    gameRateLabel.text = @"9.3";
    gameRateLabel.textColor = [UIColor redColor];
    gameRateLabel.font = [UIFont systemFontOfSize:24];
    [self.contentView addSubview:gameRateLabel];
    _gameRateLabel = gameRateLabel;
    [_gameRateLabel setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
    [_gameRateLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
    [gameRateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.contentView).offset(-78.0/3);
        make.top.equalTo(self.contentView).offset(45.0/3);
    }];
    
    
    UILabel* gameTitleLabel = [UILabel new];
    gameTitleLabel.numberOfLines = 1;
    gameTitleLabel.text = @"Star Trek Star Trek Star Trek Star Trek Star Trek ";
    gameTitleLabel.font = [UIFont systemFontOfSize:16];
    gameTitleLabel.textColor = [UIColor blackColor];
    [self.contentView addSubview:gameTitleLabel];
    _gameTitleLabel = gameTitleLabel;
    [_gameTitleLabel setContentHuggingPriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
    [_gameTitleLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
    [gameTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_gameIconImageView.mas_right).offset(48.0/3);
        make.top.equalTo(_gameIconImageView).offset(21.0/3);
        make.right.equalTo(_gameRateLabel.mas_left).offset(-55.0/3);
    }];
    
    UILabel* gameTagLabel = [UILabel new];
    gameTagLabel.numberOfLines = 1;
    gameTagLabel.text = @"Category:MMOPRG";
    gameTagLabel.font = [UIFont systemFontOfSize:14];
    gameTagLabel.textColor = [UIColor lightGrayColor];
    [self.contentView addSubview:gameTagLabel];
    _gameTagLabel = gameTagLabel;
    [_gameTagLabel setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
    [gameTagLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_gameIconImageView.mas_right).offset(48.0/3);
        make.bottom.equalTo(_gameIconImageView).offset(-21.0/3);
    }];
    
    UIView* sepLine = [UIView new];
    sepLine.backgroundColor = [UIColor lightGrayColor];
    [self.contentView addSubview:sepLine];
    [sepLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(54.0/3);
        make.right.equalTo(self.contentView).offset(-54.0/3);
        make.bottom.equalTo(self.contentView);
        make.height.equalTo(@(1));
    }];
    
    
//    gameTagLabel.alpha = 0;
//    gameRateLabel.alpha = 0;
}

- (void)loadData:(id)data indexPath:(NSIndexPath *)indexPath {
    if ([data isKindOfClass:[GameModel class]]) {
        _gameModel = data;
        
        [_gameIconImageView sd_setImageWithURL:[NSURL URLWithString:_gameModel.image]];
        _gameTitleLabel.text = _gameModel.name;
        _gameTagLabel.text = [NSString stringWithFormat:@"%@:%@", @"Category", _gameModel.category];
        _gameRateLabel.text = [NSString stringWithFormat:@"%@", @(_gameModel.point)];
    }
}

@end

注意點(diǎn)

setContentHuggingPriority和setContentCompressionResistancePriority的使用

以這個圖為例

自動布局Cell的TableView
自動布局Cell的TableView

右邊的數(shù)字和坐標(biāo)的標(biāo)題寬度都是動態(tài)數(shù)據(jù)決定的桃移,在這個場景中,我們需要實(shí)現(xiàn)的是這樣的效果:數(shù)字的優(yōu)先級比較高葛碧,數(shù)字需要完全被展示借杰,不能被壓縮,而標(biāo)題當(dāng)內(nèi)容超過邊界值进泼,需要被截取蔗衡。
從壓縮內(nèi)容角度來看: 當(dāng)標(biāo)題的文字超過了數(shù)字,被壓縮的應(yīng)該是標(biāo)題乳绕,可以查看第二個Cell的例子绞惦。因此數(shù)字的防止壓縮的優(yōu)先級比標(biāo)題的高,可以通過setContentCompressionResistancePriority方法洋措,設(shè)置數(shù)字更大的防止壓縮優(yōu)先級來達(dá)到效果
從拉伸角度來看:如果不改變對默認(rèn)的其方式济蝉,希望數(shù)字能夠一直停留在左邊,那么當(dāng)標(biāo)題沒有超過邊界值菠发,有一者是需要被拉伸的王滤,如果是數(shù)字被拉伸,那么默認(rèn)的對其方式就不會實(shí)現(xiàn)數(shù)字停留在最左邊的效果了滓鸠,所以可以通過設(shè)置拉伸的優(yōu)先級來達(dá)到效果雁乡,通過setContentHuggingPriority來設(shè)置數(shù)字比較小的優(yōu)先級實(shí)現(xiàn)。

    [_gameRateLabel setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
    [_gameRateLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];

    [_gameTitleLabel setContentHuggingPriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
    [_gameTitleLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];

總結(jié)

使用自動布局的Cell在一定的程度上提高了開發(fā)效率糜俗,不過需要注意自動布局中的某些坑蔗怠,才能讓自動布局更好的工作墩弯。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市寞射,隨后出現(xiàn)的幾起案子渔工,更是在濱河造成了極大的恐慌,老刑警劉巖桥温,帶你破解...
    沈念sama閱讀 221,548評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件引矩,死亡現(xiàn)場離奇詭異,居然都是意外死亡侵浸,警方通過查閱死者的電腦和手機(jī)旺韭,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來掏觉,“玉大人区端,你說我怎么就攤上這事“母梗” “怎么了织盼?”我有些...
    開封第一講書人閱讀 167,990評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長酱塔。 經(jīng)常有香客問我沥邻,道長,這世上最難降的妖魔是什么羊娃? 我笑而不...
    開封第一講書人閱讀 59,618評論 1 296
  • 正文 為了忘掉前任唐全,我火速辦了婚禮,結(jié)果婚禮上蕊玷,老公的妹妹穿的比我還像新娘邮利。我一直安慰自己,他們只是感情好垃帅,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,618評論 6 397
  • 文/花漫 我一把揭開白布延届。 她就那樣靜靜地躺著,像睡著了一般挺智。 火紅的嫁衣襯著肌膚如雪祷愉。 梳的紋絲不亂的頭發(fā)上窗宦,一...
    開封第一講書人閱讀 52,246評論 1 308
  • 那天赦颇,我揣著相機(jī)與錄音,去河邊找鬼赴涵。 笑死媒怯,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的髓窜。 我是一名探鬼主播扇苞,決...
    沈念sama閱讀 40,819評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼欺殿,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了鳖敷?” 一聲冷哼從身側(cè)響起脖苏,我...
    開封第一講書人閱讀 39,725評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎定踱,沒想到半個月后棍潘,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,268評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡崖媚,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,356評論 3 340
  • 正文 我和宋清朗相戀三年亦歉,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片畅哑。...
    茶點(diǎn)故事閱讀 40,488評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡肴楷,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出荠呐,到底是詐尸還是另有隱情赛蔫,我是刑警寧澤,帶...
    沈念sama閱讀 36,181評論 5 350
  • 正文 年R本政府宣布直秆,位于F島的核電站濒募,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏圾结。R本人自食惡果不足惜瑰剃,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,862評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望筝野。 院中可真熱鬧晌姚,春花似錦、人聲如沸歇竟。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽焕议。三九已至宝磨,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間盅安,已是汗流浹背唤锉。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留别瞭,地道東北人窿祥。 一個月前我還...
    沈念sama閱讀 48,897評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像蝙寨,于是被迫代替她去往敵國和親晒衩。 傳聞我的和親對象是個殘疾皇子嗤瞎,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,500評論 2 359

推薦閱讀更多精彩內(nèi)容

  • 問答題47 /72 常見瀏覽器兼容性問題與解決方案? 參考答案 (1)瀏覽器兼容問題一:不同瀏覽器的標(biāo)簽?zāi)J(rèn)的外補(bǔ)...
    _Yfling閱讀 13,759評論 1 92
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,280評論 25 707
  • 翻譯自“Auto Layout Guide”听系。 2 自動布局細(xì)則手冊 2.1 堆棧視圖 接下來的章節(jié)展示了如何使用...
    lakerszhy閱讀 1,876評論 3 9
  • 海上生明月贝奇,天涯共此時。 月兒出奇地圓潤與瑩潔靠胜。風(fēng)清月白弃秆,樹影參差,今年秋水初映月髓帽,盈盈之外的對岸菠赚,有嬌語娓娓,漸...
    宛如飛羽閱讀 323評論 1 1
  • 關(guān)于貓砂盆郑藏,下面是我買過的三個 第一種是最普通的露天的衡查,當(dāng)時肉肉只有兩個月 怕太復(fù)雜的貓砂盆他接受不了尿在外面 結(jié)...
    宋軼軼閱讀 230評論 0 0