gpt4 book ai didi

ios - 如何动态确定 UITableViewCell

转载 作者:行者123 更新时间:2023-11-29 02:30:49 25 4
gpt4 key购买 nike

假设我有一个扩展 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 *)#>]

但是当我得到cell的类类型时,我不知道如何继续。有小费吗?谢谢!

最佳答案

自 iOS 6 以来,您可以为表格 View 单元格重用标识符注册单元格类:

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

如果您不知道单元格的类型,我会抽象您的单元格类,以便它们共享父类(super class)的方法并具有不同的实现,因此至少您可以在 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;
}

关于ios - 如何动态确定 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26900444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com