简体   繁体   English

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

[英]Get next cell in UIcollectionView in Swift

I need to get the next cell inside cellForItem within a collection view so that I can update a view object. 我需要在集合视图中的cellForItem内获取下一个单元格,以便可以更新视图对象。 When I try the following below it doesn't work. 当我尝试以下操作时,它不起作用。 I've also tried indexPathForVisibleItems passing in indexPath.row + 1 and the produces an index out of range error. 我还尝试了将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
            }

Is this possible to achieve or will I need to do this via another way? 这有可能实现吗?还是我需要通过其他方式做到这一点?

Thanks 谢谢

No, it is not possible to get the cell object before initialization in cellForItemAt but here you can receive the call before displaying the cell from UICollectionViewDelegate 不,cellForItemAt初始化之前不可能获取单元格对象,但是在这里您可以在从UICollectionViewDelegate显示单元格之前接收到调用

func collectionView(_ collectionView: UICollectionView,willDisplay cell: UICollectionViewCell,forItemAt indexPath: IndexPath) {
     if let myCell = cell as? MKRCell {

     }
}

AND

If you want to set up the cell you have to setup view in the UICollectionViewDataSource 如果要设置单元格,则必须在UICollectionViewDataSource设置视图

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

}

You should update the cell in: 您应该在以下位置更新单元格:

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

Remember to modify only the cell you'll be returning from this method. 请记住,仅修改您将从此方法返回的单元格。 Other cells might not have exist at that moment. 那时可能还不存在其他单元。

Alternatively you can keep a weak reference to the cell and update it when needed. 或者,您可以保留对单元的弱引用,并在需要时进行更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM