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

时间:2015-04-21 05:50:09

标签: ios objective-c uitableview cell

我有tableView custom cell。我有能力将一些元素保存到收藏夹,当发生这种情况时,我想在image中添加一个星cell。我试图这样做,但在明星出现后,我有一个问题。我认为这是因为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;

}

3 个答案:

答案 0 :(得分:2)

替换以下代码代替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;

}

希望这对你有所帮助。

答案 1 :(得分:1)

如果对象不是TRUE

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

答案 2 :(得分:1)

是的,你是对的,因为通过带有标识符的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添加为

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