UITableViewCell initWithStyle:UITableViewCellStyleSubtitle不起作用

我在尝试在单元格中显示信息时遇到问题,一个在左侧,另一个在右侧。 我知道与UITableViewCellStyleSubtitle使用initWithStyle 。 我用这个,但似乎没有工作。

这是一些示例代码:

 - (UITableViewCell *)tableView:(UITableView *)ltableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Account Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:Cellidentifier]; } Accounts *account = [self.fetchedResultsController objectAtIndexPath]; cell.textLabel.text = account.name; cell.detailTextLabel.text = @"Price"; return cell; } 

我可以显示cell.textLabel.text很好,但是我不能得到简单的“价格”显示。 我尝试了不同的东西,比如设置cell.detailTextLabel的字体大小。

我也尝试了一些UITableViewCellStyleValue1在老职位中的build议。 将NSLog设置为“Price”后,将cell.detailTextLabel显示为null。

不知道我在做什么错。

编辑:我发现这个: cell.detailTextLabel.text是NULL

如果我删除if (cell == nil)它的工作原理…检查应该到位,那么如何使用不同的风格使它工作?

当使用故事板和原型单元格时,单元总是从出列方法返回(假定存在具有该标识符的原型)。 这意味着你永远不会进入(cell == nil)块。

在你的情况下,原型单元格没有在故事板中用字幕样式定义,所以从不使用字幕单元格,并且详细文本标签不存在。 更改故事板中的原型以获得字幕样式。

删除所有的代码,只要你只尝试这些行,并检查这将工作与否。

  -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; } cell.textLabel.text=[Array objectAtIndex:indexPath.row]; cell.detailTextLabel.text=@"Price"; return cell; } 

我看到了问题:在您的方法名称中, UITableViewvariables名为ltableView ,而不是tableView 。 将其更改为tableView

cell.detailTextLable.text应该是cell.detailTextLabel.text 。 它看起来像是一个简单的标签错误拼写。

所有这里提到的答案是真正的解决方法,即使用故事板。 这是一种只能在代码中完成的方法。

基本上,而不是注册viewDidLoad单元格的标识符在cellForRowAtIndexPath:方法只做一次。 还重置注册在viewDidLoad __sCellRegistered = 0;

  static int _sCellRegistered = 0; - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = nil; if (__sCellRegistered == 0) { __sCellRegistered = 1; NSLog(@"register cell"); cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"CellIdentifier"]; [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CellIdentifier"]; }; if (!cell) { NSLog(@"dequeue"); cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier" forIndexPath:indexPath]; }