At some point, you will need to associate different classes of cells with different types of elements in your data source. The if
may be a way. You can encapsulate this in a separate method, for example:
+(Class)cellClassForItem:(id)rowItem { Class theClass = [ UITableViewCell class ] ; if ( [ rowItem isKindOfClass:[ ... class ] ] ) { theClass = [ CellClass1 class ] ; } else if ( [ rowItem isKindOfClass:[ ... class ] ] ) { theClass = [ CellClass2 class ] ; } return theClass ; }
Or you can have every element in your a protocol
data source:
@protocol DataSourceItem <NSObject> -(Class)tableViewCellClass ; @end
Your delegation method will now look like this (assuming a second technique)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { id<DataSourceItem> item = (id<DataSourceItem>)[ tableView itemForRowAtIndexPath:indexPath ] ; Class cellClass = [ item tableViewCellClass ] ; NSString * cellID = NSStringFromClass( cellClass ) ; UITableViewCell *cell = [ tableView dequeueReusableCellWithIdentifier:cellID ] ; if ( !cell ) { cell = [ [ cellClass alloc ] initWithStyle:... reuseIdentifier:cellID ] ; } cell.value = item ; return cell; }
source share