ios 在tableview的特定单元格中放置图标- Swift

yzckvree  于 2022-12-05  发布在  iOS
关注(0)|答案(2)|浏览(155)

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

But after scrolling up and down, more stars appears:

jexiocij

jexiocij1#

试试这个:

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

9lowa7mx2#

你为什么把它放在单元格ForRowAt里?把它拿出来。那应该只用于数据。
请改用willDisplay。

相关问题