可重复使用的自定义单元格

Reusable custom cell

我有一个 tableView 和一个 custom cell。我可以将一些元素保存到收藏夹,当发生这种情况时,我想在 cell 中添加一个星号 image。我正在尝试这样做,但在星星出现后,我遇到了问题。我认为这是因为 reusable cell 但我不知道如何解决它。 我的问题是: stars appear again on the other cells even if the word is not added on favorites.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    dictionaryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell=[[dictionaryTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    }
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        cell.textLabel.text = [self.searchResult objectAtIndex:indexPath.row];

    }
    else
    {
        cell.word.text = self.tableData[indexPath.row];
        BOOL isTheObjectThere = [self.favoriteArry containsObject:self.tableData[indexPath.row]];
        if (isTheObjectThere==TRUE) {
             cell.favImg.image=[UIImage imageNamed:@"3081@3x.png"];
        }
    }

        return cell;

}

如果对象不是 TRUE

,则必须删除图像
if (isTheObjectThere==TRUE) {
   cell.favImg.image=[UIImage imageNamed:@"3081@3x.png"];
} else {
   cell.favImg.image=nil;
}

是的,你是对的,这是因为通过带有标识符 as-

的 dequeueReusableCell 重用了你的单元格
 dictionaryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

根据您的要求,您可以在单元格上设置一个星形图像,以指示相应单元格上的一些喜欢的元素,就像这样

BOOL isTheObjectThere = [self.favoriteArry containsObject:self.tableData[indexPath.row]];
        if (isTheObjectThere==TRUE) {
             cell.favImg.image=[UIImage imageNamed:@"3081@3x.png"];
        }

当任何带有星形图像的单元格被重复使用时,如果下一个单元格没有一些喜欢的元素,但如果它确实有一些喜欢的元素,那么它应该被删除,而不应该被用作-

要解决此问题,只需添加带有上述 if 语句的 else case as

if (isTheObjectThere == TRUE)
   cell.favImg.image=[UIImage imageNamed:@"3081@3x.png"];
 else
   cell.favImg.image=nil;

用以下代码代替 cellForRowAtIndexPath。你会得到你想要的输出。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    dictionaryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell=[[dictionaryTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    }
   cell.favImg.hidden = YES;
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        cell.textLabel.text = [self.searchResult objectAtIndex:indexPath.row];

    }
    else
    {
        cell.word.text = self.tableData[indexPath.row];
        BOOL isTheObjectThere = [self.favoriteArry containsObject:self.tableData[indexPath.row]];
        if (isTheObjectThere==TRUE) {
             cell.favImg.hidden = NO;
             cell.favImg.image=[UIImage imageNamed:@"3081@3x.png"];
        }
    }

    return cell;

}

希望对您有所帮助。