7

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

Roman Podymov
  • 4,168
  • 4
  • 30
  • 57
user567
  • 3,712
  • 9
  • 47
  • 80

2 Answers2

9

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)

}
Swee Kwang
  • 724
  • 9
  • 15
8

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)
}
  • I will try you solution later thank you. But It's wrote that the change happens by taping the controller, and sctually in my solution it's not possible to swipe to the next view. Is this normal? Shall I use a uipageviewcontroller and then put a uiviewcontrole on it instead of putting the uiviewcontrol directly on the collectionviewcell? – user567 Aug 09 '17 at 18:13