Copyright ? 2017年ZaneWangWang. All rights reserved.
根據(jù)項目需求實現(xiàn)功能一步步分析得到實現(xiàn)思路,最終產(chǎn)生的解決方案才是最有效的,如果你看到的不是原文請點擊查看原文
一.項目效果介紹以及需求分析
1.最近項目涉及到一個社交圈的界面,如下圖所示的效果:
2.需求介紹:在這個表中cell的子控件中,用戶發(fā)表的feeling文字要求高度自適應(yīng),發(fā)表的圖片最多為6張,可以隨機發(fā)表1~6張所以cell得整體高度主要有這兩塊的動態(tài)高度加上發(fā)表時間以及nickName不變高度的和決定烤芦。
二.方案以及實現(xiàn)
1.根據(jù)需求分析我使用xib布局了如下cell圖:
方案分析:其中由于h_1部分和h_2部分是可變的,因此我將這兩個高度約束暴露在cell的實現(xiàn)文件.m中
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *header_h;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *image_h;
2.請求數(shù)據(jù)的處理,首先在創(chuàng)建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的方法如下,其中重點是根據(jù)數(shù)據(jù)源計算文字高度和搜有圖片展示所需的高度并緩存給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.以上可以說就是準備工作了,接下來就非常簡單了,根據(jù)model的緩存高給定cell的高度即可,以下cell的配置和行高配置的兩個代理方法的實現(xiàn)
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
SocialCircleModel *model = _dataSource[indexPath.row];
//每個cell高度根據(jù)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配置數(shù)據(jù)
cell.model = _dataSource[indexPath.row];
return cell;
}
這樣的話,我們在得到網(wǎng)絡(luò)數(shù)據(jù)刷新table的時候高度就是已經(jīng)緩存好在model中的數(shù)據(jù),直接取就好了。
保留所有權(quán),未經(jīng)允許禁止轉(zhuǎn)載。