demo地址https://github.com/HeartbeatT/CellFactory
?cell在開發(fā)中經(jīng)常需要自定義,多數(shù)情況下同一個(gè)頁面的cell數(shù)據(jù)類型固定贰锁、高度固定软瞎。但對于一些頁面盅蝗,cell的樣式一樣状植,但是數(shù)據(jù)類型有多種于样。我在項(xiàng)目中遇到過一個(gè)table里面有11中數(shù)據(jù)類型抡爹。
?ok掩驱,其實(shí)不管后臺(tái)返回的list里面有多少種數(shù)據(jù)類型,肯定會(huì)返回一個(gè)字段來告訴前端數(shù)據(jù)類型冬竟,這邊我們以type字段來表示
先來看一下json格式:
[{
"type": 1,
"id": 1,
"name": "qqq"
}, {
"type": 2,
"id": 2,
"address": "www"
}]
如此的type會(huì)有很多種欧穴。在這里我們的唯一不變的就會(huì)是type類型和id這兩個(gè)字段,其余的字段會(huì)根據(jù)不同的數(shù)據(jù)類型來改變泵殴。
對于cell類型的判斷就需要使用type字段涮帘。
創(chuàng)建model基類
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, strong) id res_info;
+ (BaseModel *)jsonWithDic:(NSDictionary *)dic;
+ (BaseModel *)jsonWithDic:(NSDictionary *)dic
{
BaseModel *model = [[self alloc] init];
model.type = [[dic valueForKey:@"type"] integerValue];
if (model.type == 1)
{
model.res_info = [OneModel jsonWithDic:dic];
}
else if (model.type == 2)
{
model.res_info = [TwoModel jsonWithDic:dic];
}
return model;
}
這里暫時(shí)不需要跳轉(zhuǎn),我們先忽略id字段笑诅。res_info對應(yīng)的為具體cell數(shù)據(jù)類型
model的類型已經(jīng)搞定调缨,那么怎么需要model與cell類型綁定呢?
核心就是cellFactory
創(chuàng)建cellFactory
#import <Foundation/Foundation.h>
@class BaseModel;
@interface CellFactory : NSObject
+ (Class)cellWithModel:(BaseModel *)model;
@end
#import "CellFactory.h"
#import "BaseModel.h"
#import "OneModel.h"
#import "TwoModel.h"
#import "OneTableViewCell.h"
#import "TwoTableViewCell.h"
@implementation CellFactory
+ (Class)cellWithModel:(BaseModel *)model
{
Class className = Nil;
if ([model.res_info isKindOfClass:[OneModel class]])
{
className = [OneTableViewCell class];
}
else if ([model.res_info isKindOfClass:[TwoModel class]])
{
className = [TwoTableViewCell class];
}
return className;
}
@end
這里我們需要返回的是cell的類型吆你,方便我們結(jié)合反射機(jī)制與多態(tài)
controller里面這里只寫核心代碼弦叶,詳細(xì)請看demo
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
BaseModel *model = self.mutableArray[indexPath.row];
Class className = [CellFactory cellWithModel:model];
BaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(className)];
return cell;
}
其實(shí)這里cell就是用的多態(tài),來指向子類妇多。
如果再有新的cell樣式加進(jìn)來伤哺,對應(yīng)的每層業(yè)務(wù)非常清晰,能夠?qū)崿F(xiàn)快速開發(fā),cellFactory可以實(shí)現(xiàn)公用