代码之家  ›  专栏  ›  技术社区  ›  nevan king

为什么这个TableView代码可以工作?

  •  1
  • nevan king  · 技术社区  · 15 年前

    UITableViewCell 使用此代码:

    - (UITableViewCell *)tableView:(UITableView *)tableView
             cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"CellIdentifier";
        UITableViewCell *cell = [self.tableView
            dequeueReusableCellWithIdentifier:CellIdentifier];
    
        if (cell == nil) {
            NSLog(@"Creating cell");
            cell = [[[UITableViewCell alloc] 
                initWithStyle:UITableViewStylePlain
                reuseIdentifier:CellIdentifier] autorelease];
        }
        cell.textLabel.text = @"Hello";
        return cell;
    }
    

    UITableViewStylePlain 而不是 UITableViewCellStyleDefault . 代码运行良好,创建了新的单元格。为什么?

    3 回复  |  直到 15 年前
        1
  •  10
  •   kubi    15 年前

    这些变量就是这样定义的。

    typedef enum {
       UITableViewCellStyleDefault,
       UITableViewCellStyleValue1,
       UITableViewCellStyleValue2,
       UITableViewCellStyleSubtitle
    } UITableViewCellStyle;
    
    typedef enum {
       UITableViewStylePlain,
       UITableViewStyleGrouped
    } UITableViewStyle;
    

    两者 UITableViewCellStyleDefault UITableViewStylePlain 计算为0,所以它们可以互换。

        2
  •  3
  •   Dave DeLong    15 年前

    因为 UITableViewStylePlain 声明如下:

    typedef enum {
        UITableViewStylePlain, 
        UITableViewStyleGrouped
    } UITableViewStyle;
    

    UITableViewCellStyleDefault 声明如下:

    typedef enum {
        UITableViewCellStyleDefault,
        UITableViewCellStyleValue1,
        UITableViewCellStyleValue2,
        UITableViewCellStyleSubtitle
    } UITableViewCellStyle; 
    

    enum ,这意味着它们都将编译为 0 . 因此,它们是“可互换的”(尽管您肯定应该这样做) 依赖于生产代码中的此行为)。

        3
  •  1
  •   Douwe Maan    15 年前

    UITableViewStylePlain UITableViewCellStyleDefault

    如其他答案所述,两个常量都有相同的整数值,所以 initWithStyle:reuseIdentifier 将接收一个可以使用的样式ID,它甚至不会注意到您提供的常量与此方法无关。