Customizing UISlider — Either color or image
We're working on a pretty useful — at least we hope so — feature right now. Part of this feature is a slightly customized UISlider
. In the end, it should look pretty similar to the narrow Scollbar you know from UIScrollView
:
As this component has existed in the app before, we decided to just change the appearance of it. For me, it was the first time to work with UISlider
.
What I usually do first these days, when I have to work with something new, is to flick through Apple's documentation for something, if there's one. I opened Dash and found the "Customizing the Slider’s Appearance"-part of UISlider
. Ha, lucky me! Exactly the thing I've been looking for!
The plan was to change the thumb image using setThumbImage:ForState:
and to set minimumTrackTintColor
and maximumTrackTintColor
to white, just like this:
I wrote the code and was a bit proud of myself: Sweet Jesus, this thing turned out to be way easier than expected. Then I ran the app and sweet Jesus turned sour: Either the colors were applied or the thumb image looked good — but not both!
I looked at the documentation again, and suddenly, there was a paragraph with the headline "Debugging Sliders". I swear, it magically appeared! It wasn't there before!
Whatever, this paragraph explains the issues I had:
Use either a custom tint color or a custom image, but not both. When customizing slider appearance with images or tint, use one option or the other, but not both. Conflicting settings for track and thumb appearance are resolved in favor of the most recently set value. For example, setting a new minimum track image for any state clears any custom tint color you may have provided for minimum track images. Similarly, setting the thumb tint color removes any custom thumb images associated with the slider.
In other words: If I'd like to set a custom thumb image, I have to provide images — not colors! — for the track. And if I'd like to change the color of the track, I can't use a custom thumb image. So: it's either everything color-y or everything image-y, but not both.
Thankfully, a colleague of mine encoutered this issue before and so, he had already written a workaround: He created a category on UIColor
with a method that returns a UIImage
with this very color and a size of 1x1. The method itself looks pretty similar to this answer on StackOverflow, except it's not a category/extension on UIImage
but on UIColor
.
Using this — more or less dirty — trick I made the UISlider look like our designer has imagined.
Next time, I might read the docs even more thoroughly. Hopefully.
Anyway, thanks for reading!