iOS swift UIImageView change image in tableView cell

后端 未结 3 622
南旧
南旧 2021-01-16 22:21

I have a strange problem in tableView Custom cell. for like Image action I write these code in Custom cell called FeedViewCell

3条回答
  •  无人及你
    2021-01-16 22:59

    That's why you are changing the image loaded in the imageView and then with method tableView.dequeueReusableCell you are reusing that cell with the changed image.

    In iOS UITableView and UICollectionView apply the concept of reusable cells. They don't create one cell for every element of the array; they just create 3-4 cells and then they'll reuse it just changing the content inside. That's a great thing because it allows developers to create tables with hundreds of rows without having memory issues.

    These are the steps followed by the tableView (and also collectionView) to show the array of elements:

    1. prepareForReuse
    2. cellForRowAtIndexPath
    3. willDisplayCell

    To solve your problem you have just to check the like in the cellForRowAtIndexPath

    Example:

    func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
    
        let cell = tableView.dequeueReusableCell(withIdentifier: "FeedCell", for: indexPath) as! FeedViewCell
    
        let model = arrayOfElements[indexPath.row]
        if model.isLiked {
            cell.like.image == UIImage(named: "like-btn-active")
        } else {
            cell.like.image == UIImage(named: "like-btn-active")
        }
    
        return cell
    }
    

提交回复
热议问题