UITableViewCell样式和dequeueReusableCellWithIdentifier

Pad*_*215 18 objective-c uitableview ios

所以我注册了我的手机:

[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
}
Run Code Online (Sandbox Code Playgroud)

问题是我无法设置cell.detailTextLabel.text属性.细胞永远不会nil.

bba*_*art 32

如果首先调用,则表视图registerClass将导致dequeueReusableCellWithIdentifier在单元重用标识符匹配时返回非零单元.

我相信registerClass通常用于将成为自定义单元格的单元格UITableViewCell.您的自定义单元格可以覆盖initWithStyle并在那里设置样式.

并不总是需要创建自定义单元格.

如果要设置单元格样式,请不要调用registerClass.

  • 是的,没有注册课程就做到了.谢谢. (2认同)
  • 修复@RahulJiresal的问题是确保使用`[tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"]`而不是``tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"forIndexPath:indexPath]` (2认同)

lbs*_*eek 13

您需要做3次更改才能实现目标:

  1. 删除registerClass语句.
  2. UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; => UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  3. 使用initWithStyle:UITableViewCellStyleSubtitle

通常有两种方法可以用subtile创建单元格,首先使用自定义UITableViewCell,在init中设置样式.其次是跟随代码,这是你想要的:

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
Run Code Online (Sandbox Code Playgroud)