2

I am using UIPageControl in conjunction with UIScrollView to display 5 images. I would like to be able to set the current page indicator dot color to a different color for each page (when it is selected). I have tried setting the currentPageIndicatorTintColor in the Value Changed action of the UIPageControl, but this shows the previous color briefly before changing to the new color.

Does anyone know if its possible to use different colors for each dot, in such a way that the display is seemless?

Note: this is not a duplicate of How can i change the color of pagination dots of UIPageControl? because that question is about changing all the dots to have the same color, whereas I would like to change the individual page dots to have different colors when their page is currently showing.

Community
  • 1
  • 1
Teevus
  • 1,104
  • 1
  • 10
  • 23

2 Answers2

3

This is how you can do this:

Step 1: Subclass UIPageControl and add a property dotImages to hold images for all dots.

class MyPageControl : UIPageControl {
var dotImages : [UIImage?] = []

Step 2: Initialise your dotImages

required init(coder: NSCoder) {
    super.init(coder: coder)!

    let firstDotImage = UIImage.init(named: "dot1.png")
    let secondDotImage = UIImage.init(named: "dot2.png")
    let thirdDotImage = UIImage.init(named: "dot3.png")
    let fourthDotImage = UIImage.init(named: "dot4.png")
    let fifthDotImage = UIImage.init(named: "dot5.png")

    dotImages = [firstDotImage, secondDotImage, thirdDotImage, fourthDotImage, fifthDotImage]
}

Step 3: Implement updateDots function to set your own image

func updateDots () {
        for var index = 0; index < self.subviews.count; index++ {
        let dot = self.subviews[index] as! UIImageView
        dot.image = self.dotImages[index]
    }
}

Step 4: Call updateDots function based on you app need. You may call it initially while view is loading or may be while page is changing.

Abhinav
  • 37,684
  • 43
  • 191
  • 309
2

currentPageIndicatorTintColor WILL work. You might have to actually do a bit of work here.

func scrollViewDidScroll(scrollView: UIScrollView) {
    //If the page is over 50% scrolled change the dot to the new value.
    //If it is less, change it back if the user is holding the page.
}

What I am suggesting is listen to the scrollview, and pre-empt the page, rather than waiting for the fact to happen. My Psuedo-code is kept abstract, but if this is not enough I can modify the answer more specifically depending on your code if you provide examples.

You must therefore be a UIScrollViewDelegate

Mitchell Currie
  • 2,769
  • 3
  • 20
  • 26
  • Changing the currentPageIndicatorTintColor inside the scrollViewDidScroll function (when the scrolling results in the current page changing) works perfectly. Thanks so much – Teevus Oct 09 '15 at 05:39