Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flickering issue with UICollectionView while reloading

I'm developing an application where the user clicks on a menu item and the tableView should scroll according to the selected item.

But the problem is collectionView flicks a little bit while reloading.

Here I'm getting the visible section.

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if let firstVisibleIndexPath = self.tblRestaurantFeed.indexPathsForVisibleRows?[0]{
    self.tableViewVisibleSection = firstVisibleIndexPath.section
}}

When the variable is updating the I'm reloading the collectionview and using scroll to item

var tableViewVisibleSection:Int = 0{
didSet{
        UIView.animate(withDuration: 0.15, animations: {
            self.collectionView.reloadData()
        })
        let visibleIndexPaths = collectionView.indexPathsForVisibleItems
        let itemIndex = IndexPath(item: self.selectedTag, section: 0)
        if(!visibleIndexPaths.contains(itemIndex)){
            UIView.performWithoutAnimation {
                self.collectionView.scrollToItem(at: IndexPath(item: self.selectedTag, section: 0), at: .centeredHorizontally, animated: true)
            }
        }
}}

enter image description here

Any help will be appreciated.

like image 793
Ranjan kumar Sahu Avatar asked May 15 '26 20:05

Ranjan kumar Sahu


1 Answers

I think the problem is that you are calling .reloadData() from an animation block. Please try the code below and let me know if it works.

var tableViewVisibleSection: Int = 0 {
didSet {
        let visibleIndexPaths = collectionView.indexPathsForVisibleItems
        let itemIndex = IndexPath(item: self.selectedTag, section: 0)
        if(!visibleIndexPaths.contains(itemIndex)){
                self.collectionView.scrollToItem(at: IndexPath(item: self.selectedTag, section: 0), at: .centeredHorizontally, animated: false)
        }
}}
like image 126
Mircea Dragota Avatar answered May 18 '26 10:05

Mircea Dragota



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!