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
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)
}
}
}
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.
You can implemement scrollViewDidScroll
of UIScrollViewDelegate
for your tableView then manually scroll your UICollectionView
from there
class XYZ: UIViewController, UIScrollViewDelegate{
func viewDidLoad(){
super.viewDidLoad()
tableView.delegate = self
}
func scrollViewDidScroll(_ scrollView: UIScrollView){
let tableView = scrollView //assuming the only scrollView.delegate you conform to is the tableVeiw
collectionView.contentOffset = someMappingFrom(tableView.contentOffset) //or some other scrolling mechanism (scrollToItem)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With