Elias Al Zaghrini
Elias Al Zaghrini

Reputation: 295

Put an icon in specific cells in tableview - Swift

I am trying to make a list of contacts, and programmatically putting a star near each name where the family name is equal to a certain string, exactly like the picture below. But in fact, the problem is that when this star appears on a certain cell, when scrolling down or up, nearly the other cells will also have the star appearing. (It's like coronavirus, spreading everywhere). Is anyone able to help me fix this problem? This is my code for the TableView:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let item = self.tableArray[indexPath.row]
    
        let cell:SLF_LabelIconCell = tableView.dequeueReusableCell(withIdentifier: SLF_LabelIconCell.className) as? SLF_LabelIconCell ?? SLF_LabelIconCell()
    
        //Add a star near favorite contacts
        if item.familyName == "Zaghrini"{
           cell.favoriteIcon.isHidden=false
        }
        return cell
    }

At first glace, it appears correctly At first glace, it appears correctly But after scrolling up and down, more stars appears: After scrolling

Upvotes: 0

Views: 637

Answers (2)

Douglas W. Palme
Douglas W. Palme

Reputation: 570

Why are you putting that in the cellForRowAt? Get it out of there. That should be for data only.

Use willDisplay instead.

Upvotes: 0

Faysal Ahmed
Faysal Ahmed

Reputation: 7669

Try this:

if item.familyName == "Zaghrini" {
       cell.favoriteIcon.isHidden = false
    } else {
        cell.favoriteIcon.isHidden = true
    }

Upvotes: 1

Related Questions