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)
}
}
}}

Any help will be appreciated.
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)
}
}}
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