Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISlider Custom Thumb Shape

Tags:

swift

uislider

I want to modify a bit the UISlider. To be exact, I want the thumb to have a custom shape (square/rectangle with rounded corners and bottom shadow).

The only answers that I found were something like "Create your own custom slider". But I don't know how to do that and it would take me a lot more than just trying to modify a bit the UISlider.

From my research I found that you can assign an image to the thumb.

So my question is the following: Is there any way of "creating" a UIImage with a CGRect so I can have any shape that I want (a square/rectangle in this case)? And of course, is and implementation with the UISlider even possible?

like image 463
Lawrence413 Avatar asked Jul 08 '16 20:07

Lawrence413


2 Answers

First, create an image from of your shape.

Second, Edit the image size.

Third, Set the image of the slider for specific states:

for state: UIControlState in [.Normal, .Selected, .Application, .Reserved] {

    slider.setThumbImage(yourImageThatHasBeenResized), forState: state)

}

I don't believe you can put a UILabel on a UISlider. You would have to create the label, then align it to the same x as the slider.

like image 66
Pranav Wadhwa Avatar answered Oct 12 '22 02:10

Pranav Wadhwa


You don't need to resize your image. You can have images provided for both retina an non-retina devices. "@2x" before the image extension is a simple signifier for your program to take care of the resizing.

You can set the images like so: (Swift 4)

for state: UIControlState in [.normal, .selected, .application, .reserved] {

    slider.setThumbImage(UIImage(named: "[email protected]"), for: state)

}

// if you want a different image while dragging the slider, use the hightlighted state      
slider.setThumbImage(UIImage(named: "[email protected]"), for: .highlighted)
like image 41
Chewie The Chorkie Avatar answered Oct 12 '22 00:10

Chewie The Chorkie