Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

ios - 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

question from:https://stackoverflow.com/questions/65645563/put-an-icon-in-specific-cells-in-tableview-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...