rechsteiner / Parchment

A paging view with a highly customizable menu ✨
MIT License
3.35k stars 417 forks source link

Intercept PagingMenuItem click and scroll to index manually #716

Open tarun-personatech opened 3 months ago

tarun-personatech commented 3 months ago

This is not an issue but more of asking for help.

I need help intercepting the click on a PagingMenuItem before the associated ViewController is scrolled on the screen. By default, this click is detected from the PagingViewController's collectionView(_:didSelectItemAt:) data source method. However in my case, once the click is detected, I want to run some logic that can do one of the following:

I tried to override the collectionView(_:didSelectItemAt:) method in SelfSizingViewController from the example app like this:

override public func collectionView(_: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    DispatchQueue.main.async {
      // Run some business logic here...
      self.reloadMenu()
      self.select(index: indexPath.item, animated: true)
    }
  }

I see a couple of issues here: (on iPhone 15 Pro Max simulator)

  1. The indexPath.item doesn't have the value that you expect so the select method selects the wrong menu item. For example, if you select Once Upon a Time in the West the indexPath.item you get is 8 where it should have been 10, so Psycho gets selected. Interesting here is that Once Upon a Time in the West can be found at index 8 in visibleItems so instead of selecting by index if I do the below, the correct menu item is selected. But I wonder why the indexPath is wrong?

    let pagingItem = self.visibleItems.pagingItem(for: indexPath) self.select(pagingItem: pagingItem, animated: true)

  2. When the menu is reloaded and then the selection is made, the selection animation is messed up sometimes and the above issue remains.

I have attached a video of the same. https://github.com/rechsteiner/Parchment/assets/53808661/b581e102-f500-4f29-991b-2c5023c2b313