swift - UICollectionViewcell 一遍又一遍地调用函数

标签 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。我如何为单个单元格而不是所有单元格调用单个函数?

最佳答案

发生这种情况是因为单元格被重复使用。处理此问题的最简单方法是在 View Controller 中存储带有文本的单元格的索引路径。当单元出队时,只需检查存储数组中是否存在索引路径并相应地进行布局。

在你的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 。这也可能是问题所在。

关于swift - UICollectionViewcell 一遍又一遍地调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45483182/

相关文章:

ios - UISplitViewController从master返回到detail

ios - 从 NSMutableArray 中的解析中检索数据

types - 在 Swift 中实现闭包协议(protocol)

ios - 如何在一个 View Controller 中合并多个 Collection View ?

ios - 如何在 iOS 中显示带有动画的容器 View ?

ios - 如果可见,UICollectionViewCell 不更新图像

iOS Swift - 呈现 View Controller 并在它们之间传递信息

ios - 从图库中获取图像很慢

ios - PINCache objectForKey 返回 NSCoding 并且无法转换它

swift - Swift 中的通用完成处理程序