1

我注意到我的 cellViews 没有清除。意思是,当我向上和向下滚动时,子视图会不断增加刚刚被重用的 cellView ......我做错了什么?

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

    static NSString* cellIdentifier=@"cell";

    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if(cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
    }

    UIImageView cellView = [[UIImageView alloc] initWithFrame:rectCellFrame];

    NSError* error=nil;
    NSData* imageData = [NSData dataWithContentsOfURL:imageArray[indexPath.row] options:NSDataReadingUncached error:&error];

    UIImage* theImage= [UIImage ImageWithData:imageData];

    [cellView setImage:theImage];

    [cell addSubView:cellView];

    .
    .
    .
    .

    [cell addSubView:moreViews];

}
4

4 回答 4

1

如果您要大幅修改单元格的内容,我建议您创建一个子类UITableViewCell并引用它而不是基类。这样您就可以在子类的drawRect方法中进行更新,而不是UITableViewCell在 CFRAIP 中修改。

请注意,您还可以prepareForReuse在重用单元格之前调用单元格的方法来重置属性。

于 2013-03-12T19:04:22.753 回答
1

dequeueReusableCellWithIdentifier:返回一个单元格(而不是 nil)时,它是您之前在tableView:cellForRowAtIndexPath:方法中创建的一个单元格。首次创建时添加到该单元格的每个子视图仍在其中。如果从 获取单元格时添加更多子视图,则单元格dequeueReusableCellWithIdentifier:中将有额外的子视图。

您的tableView:cellForRowAtIndexPath:方法应具有以下基本结构:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *const kIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
            reuseIdentifier:kIdentifier];

        // code here to add subviews to cell.contentView
    }

    // code here to configure those subviews to display the content for indexPath, e.g.
    // set the image of image views and the text of labels.

    return cell;
}

棘手的部分是在单元格返回时访问子视图以设置其内容dequeueReusableCellWithIdentifier:查看Table View Programming Guide for iOS中的“以编程方式将子视图添加到单元格的内容视图”,它解释了如何使用视图标签来访问子视图。

于 2013-03-12T19:05:40.417 回答
1

您在每次方法调用时向单元格添加子视图。这意味着,当一个单元被重用时,它已经有旧的子视图。您应该在添加新的之前删除它们。例如[cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

于 2013-03-12T19:07:04.543 回答
0

每次- (UITableViewCell*)cellForRowAtIndexPath:(NSIndexPath *)indexPath调用,cellViewmoreViews再次添加到您已添加这些UIViews 的单元格中。
调用时,可重复使用的单元格不会删除它们的子视图dequeueReusableCellWithIdentifier。如果要添加子视图,最好的解决方案是子类化并在子类化的方法中UITableViewCell添加子视图initUITableViewCell

于 2013-03-12T19:01:11.953 回答