Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView - insertItems(at: indexPath) not working

I have an array with some elements in it which my UICollectionView displays. I then go and fetch more elements and append it to my array. I want to then tell the UICollectionView that elements have been added to the datasource and to update the UI.

I tried this but it is not working:

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

I get this error but I am not sure if I am doing something wrong.

EDIT: I do NOT want to use myCollectionView.reloadData()

like image 491
BlueBoy Avatar asked May 16 '26 03:05

BlueBoy


1 Answers

Your issue is that you need an IndexPath for each item you are adding to the collection view. You add multiple objects to myArray but then you only pass one IndexPath to insertItems. And this is the cause of the error.

Try the following:

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)
like image 135
rmaddy Avatar answered May 17 '26 18:05

rmaddy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!