如何动态确定UITableViewCell

时间:2014-11-13 02:41:05

标签: ios objective-c

假设我有一个扩展UITableView的CustomTableView,我想要做的是:

- (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;
}

我希望在初始化CustomTableView时确定类类型MyTblCell,类似于UICollectionView的单元格的init方法:

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

但是当我得到该类型的细胞时,我不知道该怎么做。有小费吗?谢谢!

1 个答案:

答案 0 :(得分:1)

从iOS 6开始,您可以为表视图单元重用标识符注册一个单元类:

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

然后在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;
}

如果您不知道单元格的类型,我会抽象您的单元格类,以便它们共享来自超类的方法并具有不同的实现,因此至少您可以在cellForRowAtIndexPath对比中使用类型只使用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;
}