UITableViewCell高度自適應方案(一)

Copyright ? 2017年ZaneWangWang. All rights reserved.

根據項目需求實現功能一步步分析得到實現思路,最終產生的解決方案才是最有效的,如果你看到的不是原文請點擊查看原文

一.項目效果介紹以及需求分析

1.最近項目涉及到一個社交圈的界面,如下圖所示的效果:

效果圖

2.需求介紹:在這個表中cell的子控件中,用戶發表的feeling文字要求高度自適應,發表的圖片最多為6張,可以隨機發表1~6張所以cell得整體高度主要有這兩塊的動態高度加上發表時間以及nickName不變高度的和決定。


二.方案以及實現

1.根據需求分析我使用xib布局了如下cell圖:

cell布局方案

方案分析:其中由于h_1部分和h_2部分是可變的,因此我將這兩個高度約束暴露在cell的實現文件.m中

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *header_h;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *image_h;

2.請求數據的處理,首先在創建model的屬性時,給model兩個緩存以上提及的兩個可變高度屬性,如下加粗的兩個屬性。

#import@interface SocialCircleModel : NSObject

//請求屬性

@property (strong, nonatomic) NSMutableArray *Images;

@property (strong, nonatomic) NSString *content;

@property (strong, nonatomic) NSString *totalComments;

@property (strong, nonatomic) NSString *Id;

@property (strong, nonatomic) NSString *totalPraise;

@property (strong, nonatomic) NSString *createBy;

@property (strong, nonatomic) NSString *imgHead;

@property (strong, nonatomic) NSString *createTime;

@property (strong, nonatomic) NSString *nickName;

//緩存一個可變高度給model

@property (assign, nonatomic) CGFloat header_h;

@property (assign, nonatomic) CGFloat images_h;

@end

重寫封裝model類的mj的方法如下,其中重點是根據數據源計算文字高度和搜有圖片展示所需的高度并緩存給model

+ (NSDictionary *)mj_replacedKeyFromPropertyName{

return @{@"Id":@"id"};

}

+ (instancetype)mj_objectWithKeyValues:(id)keyValues{

SocialCircleModel *model = [super mj_objectWithKeyValues:keyValues];

//替換出請求道德圖片url

[model.Images enumerateObjectsUsingBlock:^(NSDictionary? *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

[model.Images replaceObjectAtIndex:idx withObject:obj[@"imgUrl"]];

}];

//header的高度

float feelingH = [model.content getTextHeightWithShowWidth:kScreen_W - 74.0f AndTextFont:[UIFont systemFontOfSize:13.0f] AndInsets:4.0f];

if (feelingH + 50.0f < 64.0f) {

model.header_h = 64.0f;

}

else{

model.header_h = feelingH + 50.0f;

}

//圖片集的高度

float imageH = (kScreen_W - 40.0f) / 3.0f;

if (model.Images.count == 0){

model.images_h = 0;

}

else if (model.Images.count <= 3) {

model.images_h = 10.0f + imageH;

}

else{

model.images_h = 15.0f + imageH * 2.0f;

}

return model;

}

3.以上可以說就是準備工作了,接下來就非常簡單了,根據model的緩存高給定cell的高度即可,以下cell的配置和行高配置的兩個代理方法的實現

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

SocialCircleModel *model = _dataSource[indexPath.row];

//每個cell高度根據model緩存高度適配

return? model.header_h + model.images_h + 42.0f;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

SocialCircleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"socailCell" forIndexPath:indexPath];

//cell配置數據

cell.model = _dataSource[indexPath.row];

return cell;

}

這樣的話,我們在得到網絡數據刷新table的時候高度就是已經緩存好在model中的數據,直接取就好了。

保留所有權,未經允許禁止轉載。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容