我已经去了这个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/