代码之家  ›  专栏  ›  技术社区  ›  bear

自定义单元格刚刚失败

  •  1
  • bear  · 技术社区  · 15 年前

    我正在尝试使用一个自定义的uitableviewcell,并将其与uitableview控制器放在同一nib文件中。为此,文件是:ntitems.h、ntitems.m和ntitems.xib。

    我在头文件中定义了单元格:

    IBOutlet UITableViewCell *cellview;
    

    我已经正确地应用了属性:nonatomic,retain,所以它就在那里:

    @property (nonatomic, retain) IBOutlet UITableViewCell *cellview;
    

    在m文件中-我已经合成了变量设备并使用它来获取自定义单元格:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
       static NSString *CellIdentifier = @"cellview";
    
       UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
       if (cell == nil) {
        cell = self.cellview;
       }
    
       Product *aProduct = [appDelegate.products objectAtIndex:indexPath.row];
    
       name.text  = aProduct.name;
       upc.text   = [NSString stringWithFormat:@"UPC%@",aProduct.upc];
       price.text = aProduct.pid;
       return cell;
     }
    

    然而,当我上桌的时候,我却弄得一团糟:

    alt text http://dl.dropbox.com/u/1545603/tablecellissue.png

    也应该有多个单元格显示数据。现在似乎只有最后一个数据出现了。

    2 回复  |  直到 15 年前
        1
  •  1
  •   Steven Fisher    15 年前

    你不能重复使用这样一个出口的一个电池。想想看:你每次打给 tableView:cellForRowAtIndexPath: . 如果可能的话,您的工作是让tableview将单元格出列,并在每次不出列时创建一个新的单元格。

    相反,将自定义单元格存储在单独的笔尖中,并在 if (cell == nil) { } 出列失败时的代码。

    包含自定义单元格的nib文件应该有其文件的所有者nsobject,并且应该只包含单元格的nib(没有其他对象)。

    我使用此函数加载nib:

    - (id)loadObjectFromNibNamed: (NSString *)inName;
    {
        id objectsInNib = [[NSBundle mainBundle] loadNibNamed: inName
                                                         owner: self
                                                       options: nil];
         NSAssert1( objectsInNib != nil, @"loadNibNamed %@ returned nil", inName );
         NSAssert2( [objectsInNib count] == 1, @"lodNibNamed %@ returned %d items", inName, [objectsInNib count] );
         return [objectsInNib objectAtIndex: 0];
        }
    

    然后在我的 表格视图:cellforrowatindexpath: 我有:

    if ( cell == nil ) {
        cell = [self loadObjectFromNibNamed: nibName];
    }
    

    (我使用与单元重用标识符相同的nib名称。)

        2
  •  1
  •   Giao    15 年前

    现在发生的情况是,整个表只使用一个单元格。这意味着绘制的最后一个单元格是唯一可见的单元格。先前的细胞根本不存在。

    你将要查看此 document 如何从nib创建自定义表视图单元格。

    那里有一步一步的指示。