UICollectionView在分页期间不更新单元格

时间:2018-10-25 13:26:07

标签: ios swift uicollectionview uicollectionviewcell

我有一个启用了水平分页的UICollectionView,每个单元格充满了整个屏幕,并包含一个ImageView

我想要的是更新参与分页的两个单元格(如果将页面从0转到1,我想在中间进行更新)

所以我重写了以下方法:

public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        let pageWidth = collectionView.frame.size.width
        var currentPage = collectionView.contentOffset.x / pageWidth
        if (0.0 != fmodf(Float(currentPage), 1.0)) {
            currentPage += 1
        }

        let indexPath = IndexPath(row: Int(currentPage), section: 0)
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as? MyCell else {
            return
        }

        // This cell is moving out of screen
        cell.image.isHidden = true

    }

public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let pageWidth = collectionView.frame.size.width
        var currentPage = collectionView.contentOffset.x / pageWidth
        if (0.0 != fmodf(Float(currentPage), 1.0)) {
            currentPage += 1
        }

        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: IndexPath(row: Int(currentPage), section: 0)) as? MyCell else {
            return
        }
        // This cell entered the screen
        cell.image.isHidden = false
    }

问题是图像的隐藏状态的任何更改都不会生效,如果我打印cell.image.isHidden则显示正确的状态,但用户界面未更新。

1 个答案:

答案 0 :(得分:1)

每隔

guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as? MyCell else {
        return
}

使用

guard let cell = collectionView.cellForItem(at:indexPath) as? MyCell else {
        return
}