对自定义单元格使用dequeueReusableCellWithIdentifier

5 cocoa-touch objective-c ios4 ios

让我们说我有

- (UITableViewCell*)tableView:(UITableView*) cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    static NSString *cellID = @"Cell Identifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    else
    {
        return cell;
    }

    UILabel * nameLabel = [[UILabel alloc] initWithFrame: CGRectMake( 0, 15, box.size.width, 19.0f)];
    nameLabel.text = name;
    [nameLabel setTextColor: [UIColor colorWithRed: 79.0f/255.0f green:79.0f/255.0f blue:79.0f/255.0f alpha:1.0f]];
    [nameLabel setFont: [UIFont fontWithName: @"HelveticaNeue-Bold" size: 18.0f]];
    [nameLabel setBackgroundColor: [UIColor clearColor]];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    [cell addSubview: nameLabel];
}
Run Code Online (Sandbox Code Playgroud)

那会怎么样?

如果单元格不是nil,并且假设您在第5行,它是否会返回第5行的单元格,并带有确切的文本标签等?

基本上,我的问题是,如果你有标签,imageviews等你如何使用自定义的细胞cellForRowAtIndexPathdequeueReusableCellWithIdentifier

Pat*_*ley 0

是的,将已添加这些标签的单元格出列后,它们及其文本仍将保留,就像您在创建该特定单元格时离开它一样。

创建一个 UITableViewCell 子类,我们将其称为 MyTableViewCell,它具有保存所需标签/imageViews/等的属性。一旦您出列或分配了 MyTableViewCell 之一,您就可以在这些属性上设置文本/图像/等。像这样:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"identifier";

    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[MyTableViewCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:CellIdentifier];
    }



    cell.nameLabel.text = name;
    cell.imageView.image = anImage;


    return cell;
}
Run Code Online (Sandbox Code Playgroud)

您的方法的一个主要问题是围绕出列和创建的条件。在您的方法中,您仅在分配初始化时设置单元格标签(您立即返回出列的单元格而不对其进行格式化)。但是,您希望对出队单元和手动实例化单元都进行此设置。请注意这是如何在我的方法中发生的,return 语句位于最底部。这将确保创建和重用的单元格都具有适当的数据。

编辑:我遗漏的一件重要的事情是,您将在其initWithStyle: reuseIdentifier:方法中实例化单元格的属性,并将它们作为子视图添加到单元格中。这样,当您在方法中设置标签的文本(或其他内容)时cellForRowAtIndexPath,它就已经被创建了。基本上,单元格管理创建自己的视图,而 UITableView 委托只需担心用数据填充这些视图。