Skip to content

Commit

Permalink
Add delegate method to get reuse identifier for item
Browse files Browse the repository at this point in the history
  • Loading branch information
ducker committed May 7, 2015
1 parent 1383eff commit 9ae4b19
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
21 changes: 21 additions & 0 deletions TGRDataSource/TGRDataSource.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,33 @@

typedef void (^TGRDataSourceCellBlock)(id cell, id item);

@class TGRDataSource;
@protocol TGRDataSourceDelegate <NSObject>

@optional
/**
* Gets reuse identifier for cell when cellReuseIdentifier property is nil.
*
* @param dataSource The current data source
* @param item The data source item
*
* @return The reuse identifier for data source item
*/
- (NSString *)dataSource:(TGRDataSource *)dataSource reuseIdentifierForItem:(id)item;

@end

/**
Convenience class to encapsulate an `UITableView` or `UICollectionView` data source.
Inspired by http://www.objc.io/issue-1/lighter-view-controllers.html
*/
@interface TGRDataSource : NSObject <UITableViewDataSource, UICollectionViewDataSource>

/**
* The data source delegate
*/
@property (weak, nonatomic) id<TGRDataSourceDelegate>delegate;

/**
The cell reuse identifier.
*/
Expand Down
14 changes: 10 additions & 4 deletions TGRDataSource/TGRDataSource.m
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,12 @@ - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellReuseIdentifier
forIndexPath:indexPath];
id item = [self itemAtIndexPath:indexPath];
NSString * reuseIdentifier = self.cellReuseIdentifier;
if (!reuseIdentifier)
reuseIdentifier = [self.delegate dataSource:self reuseIdentifierForItem:item];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier
forIndexPath:indexPath];

if (self.configureCellBlock) {
self.configureCellBlock(cell, item);
Expand All @@ -86,9 +89,12 @@ - (NSInteger)collectionView:(UICollectionView *)collectionView
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:self.cellReuseIdentifier
forIndexPath:indexPath];
id item = [self itemAtIndexPath:indexPath];
NSString * reuseIdentifier = self.cellReuseIdentifier;
if (!reuseIdentifier)
reuseIdentifier = [self.delegate dataSource:self reuseIdentifierForItem:item];
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier
forIndexPath:indexPath];

if (self.configureCellBlock) {
self.configureCellBlock(cell, item);
Expand Down

0 comments on commit 9ae4b19

Please sign in to comment.