UICollectionView不刷新

时间:2015-03-17 03:31:30

标签: swift uicollectionview uicollectionviewcell

我正在下载一些图像并将它们插入到我的UICollectionView

这些是我的班级成员

var myItems:[UIImage] = []
var myView: UICollectionView?

我有一个接收img:UIImage对象的计时器函数。我将其插入到我的UICollectionView中,就像这样

        self.myItems.insert(img, atIndex: self.myItems.count)
        var count:Int? = self.myView?.numberOfItemsInSection(0)
        var index:NSIndexPath = NSIndexPath(forRow: count!, inSection: 0)
        self.myView?.insertItemsAtIndexPaths([index])

我也有这个功能:

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.myItems.count;
}

和这一个:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as MyCollectionViewCell
    cell.backgroundColor = UIColor.orangeColor()
    cell.textLabel.text = "Text \(indexPath.row)"
    cell.imageView.image = myItems[indexPath.row]
    cell.backgroundView = UIImageView(image: UIImage(named: "cellbg"))
    return cell
}

但我的视图并未立即显示新图像。我必须点击空白屏幕,然后新单元格显示其图像。如果有更多单元格适合视图,我也无法滚动视图。

如何刷新视图?我将单元格出列的方式有问题吗?

3 个答案:

答案 0 :(得分:4)

您忘记重新加载UICollectionView

self.myView.reloadData()

答案 1 :(得分:2)

reloadData工作不正常

然后我偶然发现了SO answer

修复问题的原因是从主线程调用reloadData。

答案 2 :(得分:-1)

Swift 4 将collection.reloadData()从cellForItemAt内部发送到主队列,它将像魅力一样发送

var cellsCount = 0
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = campaignsCollection.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell

cell.updateCell()

    // TO UPDATE CELLVIEWS ACCORDINGLY WHEN DATA CHANGES
    // AND THE 'IF CONDITION' is TO AVOID PERFORMANCE LEAK
    if cellsCount <= itemsArray.count {
        DispatchQueue.main.async {
            self.campaignsCollection.reloadData()
        }
        cellsCount += 1
    }

    return cell
}