collectionView:reloadData工作,reloadItemsAtIndexPaths没有

时间:2015-01-13 20:32:45

标签: ios swift uicollectionview

我有一个UICollectionView,其源数据有时会在屏幕外更改。为了在它返回时更新它,我写了CollectionViewController

override func viewWillAppear(animated: Bool) {
    self.collectionView!.reloadData()
}

......这样可行,但我永远不需要更新UICollectionView中的一个或两个以上的单元格,所以我认为如果用以下代码替换上述版本会更好:

override func viewWillAppear(animated: Bool) {
    self.collectionView!.reloadItemsAtIndexPaths(myArrayOfIndexPaths)
}

...但是当我这样做时,Xcode给我一个错误说:

  

postfix的操作数'!'应该有可选类型,删除'!'“。

当我删除'!'时,它表示UICollectionView没有名为reloadItemsAtIndexPaths的成员。我做错了什么?

5 个答案:

答案 0 :(得分:20)

从你的代码中看起来你已经在最后将你的collectionView声明为Optional(带?),并且可能使用@IBOutlet将它链接到你的故事板。要解决您的问题,您应该删除?来自:

@IBOutlet var collectionView: UICollectionView?

并将其替换为:

@IBOutlet var collectionView: UICollectionView!

这样你就告诉编译器你的collectionView肯定存在(因为你已经从故事板中链接了它)。

或者,您可以通过执行以下操作绑定collectionView:

if let collectionView = collectionView {
    collectionView.reloadItemsAtIndexPaths(myArrayOfIndexPaths)
}

答案 1 :(得分:6)

Swift 4 重新加载

部分中的所有项目
 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    var indexPaths: [NSIndexPath] = []
    for i in 0..<collectionView!.numberOfItems(inSection: 0) {
        indexPaths.append(NSIndexPath(item: i, section: 0))
    }
    collectionView?.reloadItems(at: indexPaths as [IndexPath])
}

答案 2 :(得分:4)

Swift 3版本代码

var indexPaths = [IndexPath]()
indexPaths.append(indexPath) //"indexPath" ideally get when tap didSelectItemAt or through long press gesture recogniser.
collectionView.reloadItems(at: indexPaths)

答案 3 :(得分:0)

如果要重新加载单个单元格,可以像下面这样指定单元格的具体内容: -

for index in indexPaths {
            if index == [0, 0] {
                print(index)
                self.collectionView?.reloadItems(at: [index])
            }
        }

希望这有帮助。

答案 4 :(得分:0)

作为一个初学者,我不知道当您将collectionView作为另一个viewController的直接子对象实现并将其实现为viewController内部的嵌入式视图时,会有所不同,也许有些开发人员正面临着相同的问题,而他们并没有这样做。不知道,如果是这样,寻找正确的方法:)

相关问题