将自定义子视图添加到UITableView中的某些可重用单元

DCM*_*xxx 2 uitableview ios

我的UITableview中有一个可重复使用的单元格,我想在某些单元格上添加自定义图像.

这是我的代码示例:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BCContactCell * cell = [tableView dequeueReusableCellWithIdentifier:contactCellIdentifier];
    ...
    if ([contact isFavorite]) {
        UIImageView * fav = [[UIImageView alloc] initWithFrame:CGRectMake(280.0f, 2.0f, 32.0f, 32.0f)];
        [fav setImage:favoriteImg]; // already loaded
        [cell addSubview:fav];
    }
}
Run Code Online (Sandbox Code Playgroud)

它的工作原理,每个最喜欢的联系人都有自己的单元格.除非我向下滑动,否则其他单元格也开始拍摄,我似乎无法弄明白.

有人可以帮我解决这个问题吗?

谢谢 !

Thi*_*ama 6

开始了,

给你的imageview提供一个标签号, fav.tag = 1290; 稍后使用该数字我们可以返回旧的uiimageview并将其从单元格中删除.
else {[[cell viewWithTag:1290] removeFromSuperview]; }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BCContactCell * cell = [tableView dequeueReusableCellWithIdentifier:contactCellIdentifier];
    ...
    if ([contact isFavorite]) {
        UIImageView * fav = [[UIImageView alloc] initWithFrame:CGRectMake(280.0f, 2.0f, 32.0f, 32.0f)];
        fav.tag = 1290;
        [fav setImage:favoriteImg]; // already loaded
        [cell addSubview:fav];
    }else{
        [[cell viewWithTag:1290] removeFromSuperview];
    }
}
Run Code Online (Sandbox Code Playgroud)

说到UITableViewCells,他们重用已经创建的单元格.当他们重用旧的一次.您必须删除添加到单元格中的UIImageView;