簡體   English   中英

在Swift中的UIcollectionView中獲取下一個單元格

[英]Get next cell in UIcollectionView in Swift

我需要在集合視圖中的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
            }

這有可能實現嗎?還是我需要通過其他方式做到這一點?

謝謝

不,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 {

}

您應該在以下位置更新單元格:

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

請記住,僅修改您將從此方法返回的單元格。 那時可能還不存在其他單元。

或者,您可以保留對單元的弱引用,並在需要時進行更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM