Adam
Adam

Reputation: 1913

Swift Changing UISlider images and tint doesn't work as expected

I have a slider in my ViewController:

@IBOutlet weak var timeSlider: UISlider!

When using the code:

timeSlider.setMinimumTrackImage(#imageLiteral(resourceName: "track"), for: .normal)
timeSlider.setMaximumTrackImage(#imageLiteral(resourceName: "track"), for: .normal)
timeSlider.setThumbImage(#imageLiteral(resourceName: "thumb2"), for: .normal)

My slider looks like this:

enter image description here

It works great and behaves as one would expect it to behave

Now I want to make the part before thumb have different color and the part after to also have different color, so I created a function which creates new images as templates (templates being an array) from images I use for my view:

func setTemplates(){
        templates.removeAll()
        for i in 0 ..< 10{
            templates.append(playImg[i].withRenderingMode(.alwaysTemplate))
        }
    }

templates[5] is the same image as "thumb2"

templates[6] = "track"

and then I wanted to assign template[6] (which the image "track" converted to template) and color it in the same fashion I do with other images in the view like buttons, or to color labels etc. like this:

timeSlider.setMinimumTrackImage(templates[6], for: .normal)
        timeSlider.setMaximumTrackImage(templates[6], for: .normal)
        timeSlider.setThumbImage(templates[5], for: .normal)
        timeSlider.minimumTrackTintColor = colors.primaryColor
        timeSlider.maximumTrackTintColor = colors.detailColor
        timeSlider.thumbTintColor = colors.secondaryColor

Where colors is a struct holding four different colors. But as you can see it doesn't work properly

enter image description here

The image thumb is being set to default one, it doesn't even behave properly as I can't move the thumb to 0.0 position of the slider and after I move it or the colors change, the part after thumb gets blue color which is default for slider.

enter image description here

I tried different ways to fight this problem but this is the closest I got it to working properly. At this point I'm starting to think it's a bug but maybe I made some mistake in my code. As I said I have buttons, labels, which I color the same way I tried here

button.setImage(templates[7], forState: .normal)
button.tintColor = colors.primaryColor

and it works What am I doing wrong?

Upvotes: 1

Views: 1589

Answers (1)

rmaddy
rmaddy

Reputation: 318774

From the documentation for UISlider thumbTintColor:

Setting this property resets the thumb images back to the slider’s default images; any custom images are released by the slider. Setting this property to nil resets the tint color to the default and removes any custom thumb images.

Same for the two track tints.

If you want custom images then just set the custom images without also setting the tints.

In other words, set either the custom images or set the tints. Do not set both.

Upvotes: 3

Related Questions