UICollectionViewcell calling functions over and over

后端 未结 1 935
Happy的楠姐
Happy的楠姐 2021-01-28 23:48

I have go this uicollectionviewcell

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
             


        
1条回答
  •  情话喂你
    2021-01-29 00:06

    This happens because cells are being reused. The easiest way to handle this is to store index paths of cells with text in your view controller. When cell is dequeued just check if index path is present in stored array and layout accordingly.

    In your ViewController

    var cellsWithText: [IndexPath] = []
    

    In cellForItemAt indexPath

    ...
    cell.postImage.image = nil
    cell.cellConstraintsWithoutImageWithText()
    if !cellsWithText.contains(indexPath) {
        cellsWithText.append(indexPath)
    }
    ...
    

    Now at the beginning at cellForItemAt indexPath

    if let CurrentPost = posts[indexPath.row] as? Post {
        if cellsWithText.contains(indexPath) {
        // layout for text
        } else {
        // layout for image
        }
    

    I also noticed that your'e using posts[indexPath.row] but your using the collectionView, that doesn't have rows and has item instead. That also might be the issue.

    0 讨论(0)
提交回复
热议问题