4

I'm trying to use pageControl option in compositional layout collection view.I already referred some previous questions related to same topic, like this Trying to hook up Compositional Layout CollectionView with PageControl. visibleItemsInvalidationHandler is not calling .It didn't work for me.Please help me if there is a way to achieve this.Your support is much appreciated.

AxSu
  • 41
  • 3
  • This works for me for an iPhone SE (2nd) with iOS 14.4: https://www.reddit.com/r/iOSProgramming/comments/fk7ynx/uicollectionview_uipagecontrol_architecture/ (first answer) – retendo Jul 13 '21 at 12:16
  • 1
    Although, for example, it does not work for me anymore on an iPhone 12 mini with iOS 14.5 (simulator and real device). The problem seems to be that the view is not updated even though the currentPage value of the page control is updated properly. – retendo Jul 13 '21 at 12:18
  • 1
    So my problem is probably not specifically related to UIPageControl in compositional layout but to updating any supplementary view in compositional layout after section.visibleItemsInvalidationHandler was called. – retendo Jul 13 '21 at 12:21

1 Answers1

1
section.visibleItemsInvalidationHandler = { [weak self] (items, offset, env) -> Void in
        guard let self = self,
              let itemWidth = items.last?.bounds.width else { return }
        
        // This offset is different from a scrollView. It increases by the item width + the spacing between items.
        // So we need to divide the offset by the sum of them.
        let page = round(offset.x / (itemWidth + section.interGroupSpacing))
        
        self.didChangeCollectionViewPage(to: Int(page))
    }

As I commented in the code snippet, the offset here is different, it sums the item width and the section spacing, so instead of dividing the offset by the content width, you need to divide it by the item width and the intergroup spacing.

It may not help you if you have different item widths, but I'm my case, where all the items have the same width, it works.