UITableviewCell 多種樣式處理(運(yùn)用多態(tài))

demo地址https://github.com/HeartbeatT/CellFactory

?cell在開(kāi)發(fā)中經(jīng)常需要自定義,多數(shù)情況下同一個(gè)頁(yè)面的cell數(shù)據(jù)類型固定、高度固定。但對(duì)于一些頁(yè)面,cell的樣式一樣,但是數(shù)據(jù)類型有多種。我在項(xiàng)目中遇到過(guò)一個(gè)table里面有11中數(shù)據(jù)類型。
?ok,其實(shí)不管后臺(tái)返回的list里面有多少種數(shù)據(jù)類型,肯定會(huì)返回一個(gè)字段來(lái)告訴前端數(shù)據(jù)類型,這邊我們以type字段來(lái)表示
先來(lái)看一下json格式:

[{
    "type": 1,
    "id": 1,
    "name": "qqq"
}, {
    "type": 2,
    "id": 2,
    "address": "www"
}]

如此的type會(huì)有很多種。在這里我們的唯一不變的就會(huì)是type類型和id這兩個(gè)字段,其余的字段會(huì)根據(jù)不同的數(shù)據(jù)類型來(lái)改變。
對(duì)于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對(duì)應(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ì)請(qǐng)看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),來(lái)指向子類。
如果再有新的cell樣式加進(jìn)來(lái),對(duì)應(yīng)的每層業(yè)務(wù)非常清晰,能夠?qū)崿F(xiàn)快速開(kāi)發(fā),cellFactory可以實(shí)現(xiàn)公用

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容