![](/img/trans.png)
[英]Custom UITableViewCell without dequeueReusableCellWithIdentifier
[英]UITableViewCell style and dequeueReusableCellWithIdentifier
所以我注册了我的手机:
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// setting up the cell
}
问题是我无法设置cell.detailTextLabel.text
属性。 细胞永远不会是nil
。
如果首先调用,则表视图registerClass
将使dequeueReusableCellWithIdentifier
在单元重用标识符匹配时返回非零单元。
我相信registerClass通常用于将是从UITableViewCell
派生的自定义单元格的单元格。 您的自定义单元格可以覆盖initWithStyle并在那里设置样式。
并不总是需要创建自定义单元格。
如果要设置单元格样式,请不要调用registerClass
。
您需要做3次更改才能实现目标:
通常有两种方法可以用subtile创建单元格,首先使用自定义UITableViewCell,在init中设置样式。 其次是跟随代码,这是你想要的:
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
尝试为单元格使用UITableViewCellStyleSubtitle样式。 将if语句中的行更改为:
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
您需要更改单元格样式:
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
对此
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
这对你有用。
最简单的方法是使用故事板,并在IB中设置单元格样式。 在这种情况下,您不应该注册任何内容,也不应该有if(cell == nil)子句。 您是否使用dequeueReusableCellWithIdentifier:或dequeueReusableCellWithIdentifier:forIndexPath似乎并不重要。 当故事板中创建该单元格时,它们都保证返回单元格。
创建自定义单元格。 在界面构建器中更改其样式。 使用表视图从视图控制器的nib中注册单元格。
和代码:
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerNib:[UINib nibWithNibName:@"YourCustomCell" bundle:nil] forCellReuseIdentifier:kReuseIdentifier];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
YourCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseIdentifier];
// Do things with the cell.
// The cell has no chance to be nil because you've already registered it in viewDidLoad method.
// So there's not need to write any code like if(cell==nil).
// Just use it.
return cell;
}
这是一个老问题。 我只是想提供一种替代解决方案。
注册单元格后,为什么不在下面尝试:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
然后做:
[cell initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier ];
这个对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.