巩鹏军的博客

HOME

Data Driven TableView

12 Dec 2018

Description

GPJDataDrivenTableView is a data-driven way to use UITableView.

GPJDataDrivenTableView has the following features:

GPJDataDrivenTableView has the following advantages:

Then, we can add/delete/modify cell independently:

Finally, our code can evolve with change of requirements harmoniously. 🎉🎉🎉Woohoo🎉🎉🎉

Usage

#import <GPJDataDrivenTableView/GPJDataDrivenTableView.h>

GPJDataDrivenTableView *dataDrivenTableView = [[GPJDataDrivenTableView alloc] initWithFrame:self.view.bounds];
dataDrivenTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
[self.view addSubview:dataDrivenTableView];

NSMutableArray *dataArray = [NSMutableArray array];
{
    ActionData *actionData = [ActionData new];
    actionData.didSelectAction = ^(id data) {
        [weakSelf actionCellReloadAction:data];
    };
    [dataArray addObject:actionData];
}
{
    ColorData *data = [ColorData new];
    data.didSelectAction = ^(id data) {
        [weakSelf colorCellAction:data];
    };
    [dataArray addObject:data];
}
[dataDrivenTableView reloadDataArray:dataArray];

Requirements

GPJDataDrivenTableView works on iOS 6+ and requires ARC to build.

Installation

CocoaPods

pod 'GPJDataDrivenTableView'

Manual

  1. download the GPJDataDrivenTableView repository
  2. copy the GPJDataDrivenTableView sub-folder into your Xcode project

Example

screenshot_basic_small

screenshot_flex_1_small screenshot_flex_2_small screenshot_flex_3_small screenshot_flex_4_small

screenshot_edit_1_small screenshot_edit_2_small screenshot_edit_3_small screenshot_edit_4_small

Origin

The traditional way is index-driven, we implement the UITableViewDataSource’s or UITableViewDelegate’s methods base on indexPath:

This index-driven way based on indexPath results a lot of if-else code segments, Various cells’ code mix together. it is error-prone, hard to evolve with change of requirements.

uitableview_indexdriven

The new way is data-driven. GPJDataDrivenTableView set itself as UITableView’s dataSource and delegate, and mapping indexPath to data in its dataArray properly and safely. we only need construct dataArray and call reloadDataArray:, that is it.

uitableview_datadriven

Using data-driven way, we don’t need concern about indexPath. it is error-free, it is friendly to evolve with change of requirements.

Implementation Choices and Details

After comparing the composite, subclass, category implementation, I choose the subclass imeplementation.

There are three classes: GPJDataDrivenTableView, GPJTableViewCell, and GPJTableViewData

The code base is only about two hundreds lines, go ahead to have a look. GPJDataDrivenTableView.m

Hope you enjoy it. github source code

关于我

专注于IM即时通讯全技术栈的程序员,关注获取更多IM技术文章。

gongpengjunblog

IM小蓝天

微信扫描二维码,关注我的公众号