UISlider Custom Thumb Shape
Asked Answered
I

2

11

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?

Intercession answered 8/7, 2016 at 20:2 Comment(2)
just change the image sizeTedda
This seems like a couple of different questions to me... A bit confusing. I suggest asking a more specific question.Forgat
F
10

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.

Forgat answered 8/7, 2016 at 20:48 Comment(2)
Thanks! I'll try it out. I have found an answer on SO that apparently works. And yes, it's aligning the label with the thumb every time it changes value.Intercession
If you want another image for the thumb while sliding the slider, use .highlighted state.Uranyl
U
7

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)
Uranyl answered 24/4, 2018 at 21:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.