仅调用一个 UICollectionViewCell 的函数

Call function for one UICollectionViewCell only

我有自定义 UICollectionViewCell,这是 cellForItemAt: 方法:

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
}

我想根据 UIImage 的不存在或存在来调用 constraint 函数,但是当一个函数被调用时,它会保留下来,所以所有的单元格都被弄乱了,因为一个单元格正在被重新使用向上滚动时。

PostCell class 的 prepareForReuse 方法中,您需要将约束恢复到原始状态

像这样

override func prepareForReuse() {
        super.prepareForReuse()
        self.yourConstraint.constant = originalValue //this is an example
    }

希望对您有所帮助

单元格初始化后添加这一行,

cell.removeConstraints(cell.constraints)

所以看起来像这样,

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PostCell
    cell.removeConstraints(cell.constraints)

    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
}