UITableViewCell initWithStyle:UITableViewCellStyleSubtitle无效

时间:2012-05-07 16:31:08

标签: ios uitableview

我在尝试在单元格中显示信息时遇到问题,一个在左边,另一个在右边。我知道将initWithStyleUITableViewCellStyleSubtitle一起使用。我使用它但它似乎不起作用。

以下是一些示例代码:

- (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,就像有些人在旧帖子中提到的那样。 设置为“Price”后抛出NSLog,将cell.detailTextLabel显示为null。

不确定我做错了什么。

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

如果我删除if (cell == nil)它有效...... 该检查应该到位,那么在使用不同的样式时如何使其工作?

5 个答案:

答案 0 :(得分:17)

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

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

答案 1 :(得分:2)

仅在尝试这些行后删除所有代码并检查这是否有效。

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

这里提到的所有答案都是一种解决方法,即使用故事板。 这是一种只在代码中执行此操作的方法。

基本上,不是在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];
}
相关问题