For one of my projects, I had to design a slider that goes from negative to positive values. Easy, isn’t it? UIKit already has a component that does the job: UISlider. But in reality, it’s a whole other matter…
If you want to customize your own slider, you will have to build it from scratch. Let’s look at this in detail.
What we want to achieve:
Let’s implement our properties:
Now that we have our properties we will be able to tackle the construction of our slider. To do this, we will override the draw() method from UIControl.
What we did is build each element of our slider. The draw method is efficient but capricious. You must imperatively build each element in the order of stacking. The first element being the base of your slider, here the backgroundLinePath and the last one will be the thumb. Imagine your slider as a multiple layer cake.
Then, to track the different interactions with our slider we will have to use these methods:
And do not forget to initialize your class:
We initialize it with a range, in this way we will only have to change this value in our ViewController to have the desired amplitude.
Let’s add an extension to our class and implement the methods update() and setup():
We setup our label which should be displayed above the thumb. And now, we finish with its position and color.
That’s it! We have completely built our slider from scratch. Just add setupSliderValueLabelInterface(thumbPath) at line 84 and roundSliderValue() at line 46 and we are done.
Thanks for reading :)
Link to the project: https://github.com/Djayl/CustomSlider