UICollectionView-insertItems(at:indexPath)不起作用

Blu*_*Boy 1 ios uicollectionview swift

我有一个数组,其中包含一些要UICollectionView显示的元素。然后,我去获取更多元素并将其附加到我的数组中。然后,我想告诉您UICollectionView元素已添加到数据源并更新UI。

我试过了,但是没有用:

// Add more data to my existing array
myArray.append(contentsOf: moreElements)
let indexPath = [IndexPath(row: myArray.count-1, section: 0)]
myCollectionView.insertItems(at: indexPath)
Run Code Online (Sandbox Code Playgroud)

我收到此错误,但不确定是否做错了。

编辑:我不想使用 myCollectionView.reloadData()

rma*_*ddy 5

您的问题是,要IndexPath添加到集合视图的每个项目都需要一个。您向添加了多个对象,myArray但随后仅将一个对象传递IndexPathinsertItems。这就是错误的原因。

请尝试以下操作:

var paths = [IndexPath]()
for item in 0..<moreElements.count {
    let indexPath = IndexPath(row: item + myArray.count, section: 0)
    paths.append(indexPath)
}

myArray.append(contentsOf: moreElements)
myCollectionView.insertItems(at: paths)
Run Code Online (Sandbox Code Playgroud)