UITableView介紹 之 AutoLayout下複雜cell的高度計算

上篇講了純代碼佈局是實現複雜cell的高度計算,下面來說述AutoLayout下cell的高度計算,因爲使用了Storyboard佈局起來比較簡單因此也給cell添加了底部的轉發評論bar,先看效果圖緩存

這裏寫圖片描述

因爲不少代碼與上篇相同,因此這篇主要將cell計算的代碼貼出來其餘的都同樣,自定義cell代碼以下ide

//
//  MTableViewCell.h
//  cell計算
//
//  Created by telek on 16/3/14.
//  Copyright © 2016年 telek. All rights reserved.
//

#import <UIKit/UIKit.h>
@class DataModel;

@interface MTableViewCell : UITableViewCell

@property (nonatomic, strong) DataModel *model;
@end

/*************************類的實現****************************/

//
//  MTableViewCell.m
//  cell計算
//
//  Created by telek on 16/3/14.
//  Copyright © 2016年 telek. All rights reserved.
//

#import "MTableViewCell.h"
#import "UIView+Expand.h"
#import "DataModel.h"

static CGFloat const margin = 10;

@interface MTableViewCell()
@property (weak, nonatomic) IBOutlet UIImageView *headIcon;
@property (weak, nonatomic) IBOutlet UILabel *nikeName;
@property (weak, nonatomic) IBOutlet UILabel *content_text;
@property (weak, nonatomic) IBOutlet UIImageView *content_image;
@property (weak, nonatomic) IBOutlet UIView *toolbar;

@end

@implementation MTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.content_text.preferredMaxLayoutWidth = [UIScreen mainScreen].bounds.size.width - 20;
}

- (void)setFrame:(CGRect)frame {
    // 使cell之間產生間距
    frame = CGRectMake(frame.origin.x, frame.origin.y + margin, frame.size.width, frame.size.height - margin);
    
    [super setFrame: frame];
}

- (void)setModel:(DataModel *)model {
    _model = model;
    
    // 設置頭像
    _headIcon.image = [UIImage imageNamed:model.icon];
    // 設置用戶名
    _nikeName.text = model.name;
    // 設置內容
    _content_text.text = model.text;
    
    // 強制AutoLayout佈局,這樣才能拿到準確的高度值
    [self layoutIfNeeded];
    // 設置圖片
    if (model.picture) {
        _content_image.hidden = NO;
        _content_image.image = [UIImage imageNamed:model.picture];
        
        // cell的高度 = 文字內容的底部 + 圖片高度 + 底部toobar的高度 + 3*間距
        model.cellHeight = _content_text.bottom + _content_image.height + _toolbar.height + 3 * margin;
    } else {
        _content_image.hidden = YES;
        // cell的高度 = 文字內容的底部 + 底部toobar的高度 + 3*間距
        model.cellHeight = _content_text.bottom  + _toolbar.height + 3 * margin;
    }
    
}
@end

註釋很清楚不用我多作解釋,下面我說一下Storyborad中佈局時須要注意的的細節佈局

  • UILabel設置了lines屬性等於0,說明顯示多行文字
  • 顯示多行文字時UILabel的高度約束不要設置
  • 底部的頭像一行和底部的toolbar基本固定能夠設定固定的約束
  • 將cell的 identitier的屬性設置好,直接能夠從緩存中取cell了

百度雲盤完整代碼地址: http://pan.baidu.com/s/1ge1c13P

相關文章
相關標籤/搜索