Detect UIPageControl page change

Viewed 6265

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

2 Answers

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)

}
Related