views:

874

answers:

1

I have added a UISlider control to an iPhone View-based application and have wired up a text field that gets the values from the slider. To fit with the user interface colors in the application I need to change the color of the slider.

With a little googling I was able to find 2 samples which do this (http://blog.hill-it.be/post/2009/03/23/Pimp-My-UISlider and http://developer.apple.com/iphone/library/samplecode/UICatalog/index.html) but I'm stuck because I'm not sure where I should be calling the code from.

I have a method which should return a custom UISlider object, but how do I override the one that I created through interface builder that lives in my sliderViewController.m and sliderViewController.h?

- (UISlider *)createCustomSlider
{
  CGRect frame = CGRectMake(174, 12.0, 120.0, 7.0);
  UISlider customSlider = [[UISlider alloc] initWithFrame:frame];
  [customSlider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
  // in case the parent view draws with a custom color or gradient, use a transparent color
  customSlider.backgroundColor = [UIColor clearColor];  
  UIImage *stetchLeftTrack = [[UIImage imageNamed:@"orangeslide.png"]
                            stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
  UIImage *stetchRightTrack = [[UIImage imageNamed:@"yellowslide.png"]
                             stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
  [customSlider setThumbImage: [UIImage imageNamed:@"slider_ball.png"]     forState:UIControlStateNormal];
  [customSlider setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
  [customSlider setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];
  customSlider.minimumValue = 0.0;
  customSlider.maximumValue = 100.0;
  customSlider.continuous = YES;
  customSlider.value = 50.0;

  return customSlider;
}

With .NET I'd normally have some code generated by the WinForms editor which I would then be able to override by creating a new object and assigning to the existing reference.

A: 

You shouldn't do it this way. You have three options:

  1. Instead of having your method return a new UISlider object, have it modify the existing UISlider instance you created in IB.
  2. Write a custom UISlider subclass and put your customization code in its awakeFromNib method. Make this class the class of the slider instance in IB.
  3. Remove the slider from the NIB completely and create it programmatically as you are doing in your method. Then add it as a subview to your mainView.
Ole Begemann