'Detect UIPageControl page change

I want to Add a UIPageController inside UICollectionViewCell. I created a custom nib file with a collectionViewCell inside. Inside the cell I added a UIPageControl.

@IBOutlet weak var pageControl: UIPageControl!
     
override func awakeFromNib() {
    super.awakeFromNib()
      
    self.isUserInteractionEnabled = true
    pageControl.isUserInteractionEnabled = true
    self.backgroundColor = UIColor.darkGray
    setupPageControl()
}

private func setupPageControl() {
    
    pageControl.numberOfPages = 7
    pageControl.translatesAutoresizingMaskIntoConstraints = false
    pageControl.currentPageIndicatorTintColor = UIColor.orange
    pageControl.pageIndicatorTintColor = UIColor.lightGray.withAlphaComponent(0.8)
}

How can I detect the page change? Also the dots are in the middle of the view, is it possible to put them on the middle?

enter image description here



Solution 1:[1]

enter image description here From Apple Documentation

When a user taps a page control to move to the next or previous page, the control sends the valueChanged event for handling by the delegate. The delegate can then evaluate the currentPage property to determine the page to display. The page control advances only one page in either direction. The currently viewed page is indicated by a white dot. Depending on the device, a certain number of dots are displayed on the screen before they are clipped.

Also you can use

func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
    let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
    pageControl.currentPage = Int(pageNumber)
}

Solution 2:[2]

Swift 5

1) addTaget

You can add a target that detect value change on your setupPageControl functions:

private func setupPageControl() {

    pageControl.numberOfPages = 7
    pageControl.translatesAutoresizingMaskIntoConstraints = false
    pageControl.currentPageIndicatorTintColor = UIColor.orange
    pageControl.pageIndicatorTintColor = UIColor.lightGray.withAlphaComponent(0.8)
    pageControl.addTarget(self, action: #selector(pageControlHandle), for: .valueChanged)
}

Create a selector to change the value that you wants:

@objc private func pageControlHandle(sender: UIPageControl){
    print(sender.currentPage)

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Swee Kwang