Besi
Besi

Reputation: 22959

Approach to create a custom slider

I need the following slider control.

I currently see the following approaches, which both seem to have their pros and cons:

  1. Create a UISlider subclass and add new properties and functionality to it
  2. I create a custom control with a UIView which contains a UISlider and a UIProgressBar and provide an API similar to the one of UISlider.
  3. I create the control from scratch with custom drawing code.

I am not sure if there are some aspects that I have missed. I am now wondering which approach is the most suitable for my problem.

Upvotes: 0

Views: 1240

Answers (2)

DShah
DShah

Reputation: 9876

Below are the few links which shows how you can create a custom slider :

  1. https://github.com/barrettj/BJRangeSliderWithProgress
  2. https://github.com/cbpowell/CPSlider
  3. https://github.com/buildmobile/iosrangeslider
  4. https://github.com/taviscaios/TVCalibratedSlider
  5. https://github.com/ole/OBSlider

Note: Normally for creating any UI custom control you can simply inherit the class from UIControl class which will allow you to have all the properties of the class that you want and other properties also... but be careful of using it....

Upvotes: 2

Suhail Patel
Suhail Patel

Reputation: 13694

I think option 2 and 3 are a stretch. What you could do is have a method which is called when the slider value is changed which sets it to the maximum in the middle if the user goes beyond the values they are allowed on the track:

Declare your slider instance with something similar to this (the main bit is the add target)

UISlider *slider = [[UISlider alloc] initWithFrame:CGRectZero];
slider.continuous = TRUE;
slider.minimumValue = MIN_VALUE;   // some min value constant or something?
slider.maximumValue = SLIDER_MAX_VALUE;  // some max value constant for the entire slider
slider.value = MIN_VALUE;   // or anything else you want

[slider addTarget:self action:@selector(checkBeyondTrack:) forControlEvents:UIControlEventValueChanged];
[self.contentView addSubview:slider];

Now you need the checkBeyondTrack method in the same class as where you defined the slider

- (void)checkBeyondTrack:(id)sender {
    UISlider *slider = sender;        

    // if we've attempted to go beyond the value allowed
    if (slider.value > MAX_TRACK) {
        [slider setValue:MAX_TRACK animated:YES];
    }
}

Every time the value of the slider is changed by the users, the slider target method checkBeyondTrack: will be called which performs the check and resets the value as necessary.

Upvotes: 0

Related Questions