在Swift中的UIcollectionView中获取下一个单元格

时间:2017-10-24 09:35:58

标签: ios swift uicollectionview indexpath

我需要在集合视图中获取cellForItem中的下一个单元格,以便我可以更新视图对象。当我尝试以下方法时,它不起作用。我也尝试indexPathForVisibleItems传递indexPath.row + 1并生成索引超出范围错误。

    let index = IndexPath(row: indexPath.row + 1, section: indexPath.section)
            if let nextCell = collectionView.cellForItem(at: index) as! MKRCell {
                nextCell.setupWaitView(time: timeToWait)
                nextCell.waitViewHeightConstraint.constant = 80
                nextCell.waitView.alpha = 1
                nextCell.waitView.isHidden = false
            }

这可能实现,还是需要通过其他方式实现?

由于

2 个答案:

答案 0 :(得分:1)

不,cellForItemAt初始化之前无法获取单元格对象,但这里 您可以在显示UICollectionViewDelegate

中的单元格之前接听电话
func collectionView(_ collectionView: UICollectionView,willDisplay cell: UICollectionViewCell,forItemAt indexPath: IndexPath) {
     if let myCell = cell as? MKRCell {

     }
}

如果要设置单元格,则必须在UICollectionViewDataSource

中设置视图
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

}

答案 1 :(得分:1)

您应该更新单元格:

func collectionView(_ collectionView: UICollectionView, 
    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell

请记住仅修改您将从此方法返回的单元格。那时其他细胞可能不存在。

或者,您可以保留对单元格的弱引用,并在需要时更新它。