UICollectionViewcell一遍又一遍地调用函数

时间:2017-08-03 11:42:16

标签: swift

我已经去了这个uicollectionviewcell

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PostCell
    if let CurrentPost = posts[indexPath.row] as? Post{
        //determine which constraint to call
        if(CurrentPost.PostText != nil){
            if(CurrentPost.PostImage != nil){
                cell.postImage.image = CurrentPost.PostImage
                cell.cellConstraintsWithImageWithText()
            }else{
                cell.postImage.image = nil
                cell.cellConstraintsWithoutImageWithText()
            }
        }else{
            cell.postImage.image = CurrentPost.PostImage
            cell.cellConstraintsWithImageWithoutText()
        }
    }
    return cell
}

我的目标是根据图像和文本的缺失或存在来确定目标函数。现在问题是所有这些函数都被调用,因为有些单元格正在调用图像cellConstraintsWithImageWithText,而其他单元格则没有让它们如此cellConstraintsWithoutImageWithText被调用。如何为单个细胞而不是所有细胞调用单个函数?

1 个答案:

答案 0 :(得分:0)

这是因为正在重复使用细胞。处理此问题的最简单方法是在视图控制器中存储带有文本的单元格的索引路径。当单元格出列时,只需检查存储的数组和布局中是否存在索引路径。

ViewController

var cellsWithText: [IndexPath] = []

cellForItemAt indexPath

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

现在开始于cellForItemAt indexPath

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

我还注意到你使用posts[indexPath.row],但你使用的是collectionView,它没有行,而是item。这也可能是问题所在。

相关问题