views:

1239

answers:

3

Hi everyone!

My first question on stackoverflow!

I'm using a UISlider in my app but I'd like to use a custom "look-and-feel" for it. I have changed the thumb to my own image but is there a way to change the bar also? I have a bar image I would like to use but can't see how to do this.

I have found how to change the max and min image but not the bar itself.

Thanks

Oliver

A: 

You need to subclass UISlider and override:

- (CGRect)trackRectForBounds:(CGRect)bounds

Discussion You should not call this method directly. If you want to customize the track rectangle, you can override this method and return a different rectangle. The returned rectangle is used to scale the track and thumb images during drawing.

willcodejavaforfood
+2  A: 

You were right to use -setMinimumTrackImage:forState: and -setMaximumTrackImage:forState: methods. What you missed is that you should provide stretchable UIImages to them, the rest is taken care of automagically:

UIImage *sliderLeftTrackImage = [[UIImage imageNamed: @"SliderMin.png"] stretchableImageWithLeftCapWidth: 9 topCapHeight: 0];
UIImage *sliderRightTrackImage = [[UIImage imageNamed: @"SliderMax.png"] stretchableImageWithLeftCapWidth: 9 topCapHeight: 0];
[mySlider setMinimumTrackImage: sliderLeftTrackImage forState: UIControlStateNormal];
[mySlider setMaximumTrackImage: sliderRightTrackImage forState: UIControlStateNormal];

You can use the same image for both the min and max parts.

Costique
+2  A: 

The simplest solution would be to render a UIImage behind the control to represent the track. The thumbknob can be changed with:

[mySlider setThumbImage:[UIImage imageNamed:@"thumb_image.png"] forState:UIControlStateNormal];

A side-effect of this is that the track isn't rendered unless you provide your own. This, combined with the UIImage, provide you with a custom UISlider without you having to subclass anything.

Steve Melvin