仅为一个UICollectionViewCell调用函数

时间:2017-08-03 13:13:57

标签: ios swift nslayoutconstraint

我有自定义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
}

我想根据constraint的缺席或存在调用UIImage函数,但是当一个函数被调用时,它会保持不变,因为滚动时正在重新使用一个单元格备份。

2 个答案:

答案 0 :(得分:3)

prepareForReuse课程的PostCell方法中,您需要将约束恢复为原始状态

类似这样的事情

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

希望这个帮助

答案 1 :(得分:2)

在单元初始化后添加此行,

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
}