2017-08-12 133 views
1

我有一個數組,其中有一些元素,我的UICollectionView顯示。然後我去獲取更多元素並將其附加到我的數組中。然後我想告訴UICollectionView已將元素添加到數據源並更新UI。UICollectionView - insertItems(at:indexPath)不起作用

我試過,但它不工作:

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

我得到這個error,但我不知道如果我做錯了什麼。

編輯:我不想使用myCollectionView.reloadData()

回答

2

你的問題是,你需要一個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) 
+0

我得到一個錯誤,因爲我有一個頁腳:'沒有UICollectionViewLayoutAttributes實例爲-layoutAttributesForSupplementaryElementOfKind:UICollectionElementKindSectionFooter' – BlueBoy

+0

這是一個全新的問題,超出了你在這個問題中提出的問題。作爲一個時間關注一個問題。 – rmaddy

+0

好的。您的解決方案效果很好(當沒有頁腳時)。我將不得不弄清楚我的頁腳還在發生什麼。 – BlueBoy

0

嘗試:

myArray.append(contentsOf: moreElements) 
myCollectionView.reloadData() 

而且在numberOfItemsInSection數據源的方法:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return myArray.count 
} 
+0

如果'myArray'目前是空這將崩潰。 – rmaddy

+0

是的,已經更新了我的答案。 –

+0

好的,但你對問題的初始描述是錯誤的。看到我的答案爲實際的原因。 – rmaddy