SanjayPathak
SanjayPathak

Reputation: 121

How to reload only the visible sections of a UICollectionView?

I am trying to change the number of items in section depending on the orientation of the device.

I have achieved it by reloading the entire collection view in viewWillTransitionToSize and changing the number of "maximum permissible items in section" in number of sections in UICollectionView.

This is not the best way as I can see we can load specific sections. Please share if you can come up with a better solution.

Upvotes: 3

Views: 3642

Answers (2)

Matloob Hasnain
Matloob Hasnain

Reputation: 1037

    NSSet *visibleSections = [NSSet setWithArray:[[self.tableView indexPathsForVisibleRows] valueForKey:@"section"]];

//Reloading Section

[self.myCollectionView reloadSections:visibleSections];

Upvotes: 2

Fran Martin
Fran Martin

Reputation: 2369

You can reload a specific section using the code below:

let table = UITableView()
let index = IndexSet.init(integer: 0) //The section to reload
table.reloadSections(index, with: UITableViewRowAnimation.automatic)

If you want to do it depending of your visible sections you will need to get the visible cells like this: table.visibleCells

And create the indexes of section to reload from these visible cells

let table = UITableView()
var indexes = IndexSet()
let visibleCells = table.visibleCells
for cell in visibleCells {
    indexes.insert((table.indexPath(for: cell)?.section)!)
}
table.reloadSections(indexes, with: UITableViewRowAnimation.automatic) 

Upvotes: 3

Related Questions