Search code examples
iosuitableviewuicollectionviewscrollviewswift4.2

Auto scroll UICollectionView when I scroll UITableview


I have a horizontal CollectionView on top and TableView under it I want as I scroll TableView my CollectionView should scroll and animate along with to some level I have achieved with scrollItemTo but CollectionView scrolling to slow but I want it working as it is working in uberEats iOS app in restaurant items list details and same is working in urbanClap app

It's like moving a view cell by cell as table view section header reach top


Solution

  • The uber eats app functionality that you're referring works like: whenever a particular section of tableView reaches the top, that particular collectionViewCell is selected.

    As evident from the above statement,

    number of items in collectionView = number of sections in tableView

    You can achieve the solution to this particular problem by tracking the top visible section index of tableView and then selecting the collectionViewCell at that particular index, i.e.

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView === self.tableView {
            if
                let topSectionIndex = self.tableView.indexPathsForVisibleRows?.map({ $0.section }).sorted().first,
                let selectedCollectionIndex = self.collectionView.indexPathsForSelectedItems?.first?.row,
                selectedCollectionIndex != topSectionIndex {
                let indexPath = IndexPath(item: topSectionIndex, section: 0)
                self.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
            }
        }
    }
    

    enter image description here

    Changing collectionViewCell color on selection:

    Create a custom UICollectionViewCell and override **isSelected** property to handle selected and un-selected state, i.e.

    class CollectionViewCell: UICollectionViewCell {
        @IBOutlet weak var titleLabel: UILabel!
    
        override var isSelected: Bool {
            didSet {
                if self.isSelected {
                    self.contentView.backgroundColor = #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)
                } else {
                    self.contentView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
                }
            }
        }
    }
    

    You won't need to manually update the backgroundColor of cell elsewhere after this.