How to connect UIPageControl to UICollectionView (Swift)

I am currently using UICollectionView to display 3 images (each image spans the entire cell). I also have a UIPageControl that I placed on top of the UICollectionView. I want the UIPageControl to show the number of images (in this case 3), as well as the image that the user is currently viewing. The effect I'm trying to use is the Instagram app.

The way I'm currently using to achieve this effect is to place the UIPageControl update in the UICollectionView function willDisplay, for example:

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    pictureDots.currentPage = indexPath.item
}

This allows you to properly connect the swap effect between the collection view and page management. However, the problem is that the UIPageControl starts to say that the user is in the third image, even if he is displaying the first image.

Does anyone know why this is happening and how to solve this problem?

+4
source share
1 answer

First add UIPageControlto your storyboard with UICollectionView, and then connect them as outputs to the view controller.

@IBOutlet var pageControl: UIPageControl!
@IBOutlet var collectionView: UICollectionView!

Adjust your method numberOfItemsInSectionin UICollectionViewDataSourceto set the page control counter to always equal the number of cells in the collection view.

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    let count = ...

    pageControl.numberOfPages = count
    pageControl.isHidden = !(count > 1)

    return count
}

, UIScrollViewDelegate, , UICollectionView . UICollectionViewController, .

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

    pageControl?.currentPage = Int(scrollView.contentOffset.x) / Int(scrollView.frame.width)
}

func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {

    pageControl?.currentPage = Int(scrollView.contentOffset.x) / Int(scrollView.frame.width)
}

, a UICollectionView a UIScrollView .

+8

Source: https://habr.com/ru/post/1690539/


All Articles