3

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.

Lal Krishna
  • 15,485
  • 6
  • 64
  • 84

2 Answers2

1

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)
        }
}}
Mircea Dragota
  • 644
  • 7
  • 17
0

Try below one.

var currentMenu: Int = 0

override func viewDidLoad() {
        ...
        
        collectionView.selectItem(at: IndexPath(item: currentMenu, section: 0), animated: true, scrollPosition: [])
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        currentMenu = indexPath.row
        tableView.scrollToRow(at: IndexPath(item: 0, section: currentMenu), at: .top, animated: true)
        collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard let indexPath = tableView.indexPathsForVisibleRows?.first, abs(indexPath.section - currentMenu) == 1, scrollView.isDragging else { return }
        currentMenu = indexPath.section
        collectionView.selectItem(at: IndexPath(item: currentMenu, section: 0), animated: true, scrollPosition: .centeredHorizontally)
    }
}
Lal Krishna
  • 15,485
  • 6
  • 64
  • 84