itenyh
itenyh

Reputation: 1939

How to dynamically determine the UITableViewCell

Say I have a CustomTableView which extends UITableView, what I want to do is :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath   *)indexPath
{
    static NSString *idStr = @"id";
    MyTblCell *cell = [tableView dequeueReusableCellWithIdentifier:idStr];
    if (!cell) cell = [[MyTblCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:id1];
return cell;
}

I want the class type MyTblCell to be determined when I intialize the CustomTableView, something like the init method of the cell of the UICollectionView:

[collectionView registerClass:<#(__unsafe_unretained Class)#> forCellWithReuseIdentifier:<#(NSString *)#>]

But I don`t know how to go on when I get the class type of the cell. Any tips? Thanks!

Upvotes: 0

Views: 43

Answers (1)

Aaron Wojnowski
Aaron Wojnowski

Reputation: 6480

Ever since iOS 6, you could register a cell class for a table view cell reuse identifier:

[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];

Then in your cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath   *)indexPath
{
    static NSString * identifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    // do something with the cell (no need for a nil check)
    return cell;
}

If you don't know the type of the cell, I would abstract your cell classes so they share methods from a superclass and have different implementations so at least you could have a type in your cellForRowAtIndexPath versus just using id.

- (instancetype)init {

    // ...
    [tableView registerClass:[CustomCellClassSubclass class] forCellReuseIdentifier:@"Cell"];
    // ...

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath   *)indexPath
{
    static NSString * identifier = @"Cell";
    CustomCellClass *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    // use some CustomCellClass methods
    return cell;
}

Upvotes: 1

Related Questions