Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to hook up Compositional Layout CollectionView with PageControl. visibleItemsInvalidationHandler is not calling

I want to implement paging on a welcome screen in iOS app (iOS 13, swift 5.2, xcode 11.5).

For this purpose, I use a UICollectionView and UIPageControl. Now I need to bind pageControl to Collection view.

At first, I tried to use UIScrollViewDelegate but soon found out that it does not work with the compositional layout. Then I discovered visibleItemsInvalidationHandler which is available for compositional layout sections. I tried different options like this:

section.visibleItemsInvalidationHandler = { (visibleItems, point, env) -> Void in
   self.pageControl.currentPage = visibleItems.last?.indexPath.row ?? 0 
}

and like this:

section.visibleItemsInvalidationHandler = { items, contentOffset, environment in
    let currentPage = Int(max(0, round(contentOffset.x / environment.container.contentSize.width)))
    self.pageControl.currentPage = currentPage
}

but nothing works...

Seems like that callback is not triggering at all. If I place a print statement inside of it it is not executed.

Please find below the whole code:

import Foundation
import UIKit

class WelcomeVC: UIViewController, UICollectionViewDelegate {
    
    //MARK: - PROPERTIES
    var cardsDataSource: UICollectionViewDiffableDataSource<Int, WalkthroughCard>! = nil
    var cardsSnapshot = NSDiffableDataSourceSnapshot<Int, WalkthroughCard>()
    var cards: [WalkthroughCard]!
    var currentPage = 0
    
    
    //MARK: - OUTLETS
    @IBOutlet weak var signInButton: PrimaryButton!
    
    @IBOutlet weak var walkthroughCollectionView: UICollectionView!
    
    @IBOutlet weak var pageControl: UIPageControl!
    
    //MARK: - VIEW DID LOAD
    override func viewDidLoad() {
        super.viewDidLoad()
        walkthroughCollectionView.isScrollEnabled = true
        walkthroughCollectionView.delegate = self
        setupCards()
        pageControl.numberOfPages = cards.count
        configureCardsDataSource()
        configureCardsLayout()
    }
   
    //MARK: - SETUP CARDS
    
    func setupCards() {
        cards = [
            WalkthroughCard(title: "Welcome to abc", image: "Hello", description: "abc is an assistant to your xyz account at asdf"),
            WalkthroughCard(title: "Have all asdf projects at your fingertips", image: "Graphs", description: "Enjoy all project related data whithin a few taps. Even offline")
        ]
    }
    
    //MARK: - COLLECTION VIEW DIFFABLE DATA SOURCE
    
    private func configureCardsDataSource() {
        cardsDataSource = UICollectionViewDiffableDataSource<Int, WalkthroughCard>(collectionView: walkthroughCollectionView) {
            (collectionView: UICollectionView, indexPath: IndexPath, card: WalkthroughCard) -> UICollectionViewCell? in
            // Create cell
            guard let cell = collectionView.dequeueReusableCell(
                withReuseIdentifier: "WalkthroughCollectionViewCell",
                for: indexPath) as? WalkthroughCollectionViewCell else { fatalError("Cannot create new cell") }
            //cell.layer.cornerRadius = 15
            cell.walkthroughImage.image = UIImage(named: card.image)
            cell.walkthroughTitle.text = card.title
            cell.walkthroughDescription.text = card.description
            return cell
        }
        setupCardsSnapshot()
    }
    
    private func setupCardsSnapshot() {
        cardsSnapshot = NSDiffableDataSourceSnapshot<Int, WalkthroughCard>()
        cardsSnapshot.appendSections([0])
        cardsSnapshot.appendItems(cards)
        cardsDataSource.apply(self.cardsSnapshot, animatingDifferences: true)
    }
    
    
    //MARK: - CONFIGURE COLLECTION VIEW LAYOUT
    func configureCardsLayout() {
        walkthroughCollectionView.collectionViewLayout = generateCardsLayout()
    }
    
    func generateCardsLayout() -> UICollectionViewLayout {
        
        let itemSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1.0),
            heightDimension: .fractionalHeight(1.0))
        let fullPhotoItem = NSCollectionLayoutItem(layoutSize: itemSize)

        
        let groupSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1.0),
            heightDimension: .fractionalHeight(1.0))
        let group = NSCollectionLayoutGroup.horizontal(
            layoutSize: groupSize,
            subitem: fullPhotoItem,
            count: 1
        )
        
        let section = NSCollectionLayoutSection(group: group)
        section.orthogonalScrollingBehavior = .groupPagingCentered
        let layout = UICollectionViewCompositionalLayout(section: section)
        
        //setup pageControl
        section.visibleItemsInvalidationHandler = { (items, offset, env) -> Void in
            self.pageControl.currentPage = items.last?.indexPath.row ?? 0
        }
        
        return layout
    }
    
 
}
like image 284
Oleg Titov Avatar asked Oct 28 '25 04:10

Oleg Titov


2 Answers

It should be working if you set up the invalidation handler for the section before passing the section to the layout:

let section = NSCollectionLayoutSection(group: group)
section.orthogonalScrollingBehavior = .groupPagingCentered
section.visibleItemsInvalidationHandler = { (items, offset, env) -> Void in
    self.pageControl.currentPage = items.last?.indexPath.row ?? 0
}

return UICollectionViewCompositionalLayout(section: section)
like image 138
Dimitri Avatar answered Oct 30 '25 18:10

Dimitri


Maybe this solution might helps.

It's pretty simple and it worked smoothly for me

section.visibleItemsInvalidationHandler = { [weak self] _, offset, environment in
    guard let self else { return }
    
    let pageWidth = environment.container.contentSize.width
    let currentPage = Int((offset.x / pageWidth).rounded())
    self.pageControl.currentPage = currentPage
}
like image 38
scarpz Avatar answered Oct 30 '25 18:10

scarpz