Search code examples
swiftuicollectionviewuiscrollviewuikituiscrollviewdelegate

Swift 5: scrollViewDidScroll not called in UICollectionView class


Yes, I've checked other questions regarding this topic. For some reason, the function

override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    print(scrollView.contentOffset)
}

is not called inside my UICollectionView class.

Here is the full class. I basically want to update my pageControl when user swipes on each cell. I tried collectionView:willDisplayCell:forItemAtIndexPath: method but i found that sometimes when I scroll and stop midway the cell and come back, it is not updating to the previous value. Hence why i resorted to the scrollview delegate.

class FilterInfoImagesCollectionViewController: UICollectionViewController {

    var selectedFilterCollection: FilterCollection!
    private let pageControl: UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.currentPage = 0
        pageControl.numberOfPages = 5 // Hardcoded since we know there will only be 5 example images
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        return pageControl
    }()
    private var datasource: DataSource!
    private var datas = [FilterInfo]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView.alwaysBounceVertical = false
        collectionView.isPagingEnabled = true
        collectionView.register(FilterInfoCollectionViewCell.self, forCellWithReuseIdentifier: FilterInfoCollectionViewCell.ReuseIdentifier)
        collectionView.collectionViewLayout = createLayout()
        collectionView.backgroundColor = .clear
        
        collectionView.delegate = self
        collectionView.dataSource = self

        configureDatasource()
        setupDatas()
        
        setupView()
        setupConstraint()
    }
    
    private func setupDatas() {
        let filterName = selectedFilterCollection.name.components(separatedBy: " ").first!
        for n in 1 ... 5 {
            let image = UIImage(named: "\(filterName).ex\(n)")
            
            let filterInfo = FilterInfo(image: image, filterName: "\(filterName)\(n)")
            datas.append(filterInfo)
        }
        
        self.createSnapshot(from: datas)
    }
    
    private func setupView() {
        self.view.addSubview(pageControl)
    }
    
    private func setupConstraint() {
        pageControl.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }
}

extension FilterInfoImagesCollectionViewController {
    fileprivate enum Section { case main }
    fileprivate typealias DataSource = UICollectionViewDiffableDataSource<Section, FilterInfo>
    fileprivate typealias Snapshot = NSDiffableDataSourceSnapshot<Section, FilterInfo>
    
    
    fileprivate func configureDatasource() {
        datasource = DataSource(collectionView: collectionView!, cellProvider: { (collectionView, indexPath, filterInfo) -> UICollectionViewCell? in
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FilterInfoCollectionViewCell.ReuseIdentifier, for: indexPath) as? FilterInfoCollectionViewCell else { return nil }
            
            cell.filterInfo = filterInfo
            
            return cell
        })
    }
    
    fileprivate func createSnapshot(from datas: [FilterInfo]) {
        var snapshot = Snapshot()
        snapshot.appendSections([.main])
        snapshot.appendItems(datas)
        datasource.apply(snapshot, animatingDifferences: true)
    }
    
    private func createLayout() -> UICollectionViewLayout {
        
        let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1))
        let item = NSCollectionLayoutItem(layoutSize: itemSize)
        
        let groupSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1),
            heightDimension: .fractionalHeight(1))
        let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: 1)
        
        let section = NSCollectionLayoutSection(group: group)
        section.orthogonalScrollingBehavior = .groupPaging
        
        let layout = UICollectionViewCompositionalLayout(section: section)
        return layout
    }
}

extension FilterInfoImagesCollectionViewController {
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print(scrollView.contentOffset)
    }
}

How come it is not called? I tried to check with other scrollview delegate methods and the same thing happen - not called.

UPDATE: Added delegate and datasource to self as per request


Solution

  • Add in viewDidLoad. scroll function related to UICollectionViewDelegate and you need to set the delegate for using your override functions

    section.visibleItemsInvalidationHandler = { [weak self] visibleItems, point, environment in
        self?.pager.currentPage = visibleItems.last!.indexPath.row
    }