Search code examples
iphoneiosuislider

Can you customize UISlider like the "unlock slider" in iPhone?


I have a question about UISliders in IOS and to what extent you can customize them?
I would like to implement a slider like the "Unlock slider" in iPhone.
But it seems like IOS have not provided any "standard" ways for implementing a slider like this?.

Is it possible to implement a standard UISlider and set it to a min.value (0.0) and maximum.value (0.5). If the slider "hits" a value greater then (0.01) it should automatically be pulled back to the min.value (0.0).
If it hits the maximum value (0.5), start an event then automatically pulled back to min.value?

All help is appreciated!


Solution

  • Try this. I use this in my Project

    Slider.h

    @class Slider;
    @protocol SliderDelegate <NSObject>
    @required
    - (void) slideEnd;
    @end
    @interface Slider : UISlider
    @property (nonatomic, weak) id<SliderDelegate> delegate;
    

    Slider.m

    - (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
    if (self) {
        [self setMinimumTrackImage:YOUR_MINIMUM_TRACK_IMG forState:UIControlStateNormal];
        [self setMaximumTrackImage:YOUR_MAXIMUM_TRACK_IMG  forState:UIControlStateNormal];
        [self setThumbImage:YOUR_THUMB_IMAGE];
        self.minimumValue = 0.0;
        self.maximumValue = 1.0;
        self.value = 0.0;
        [self addTarget:self action:@selector(moved:) forControlEvents:UIControlEventTouchUpInside];
        [self addTarget:self action:@selector(moved:) forControlEvents:UIControlEventTouchUpOutside];
    }
        return self;
    }
    
    - (void) moved:(UISlider *) sender
    {
        if (self.value != 1.0) {
            [self setValue: 0 animated: YES];
    
        } else {
            [[self delegate] slideEnd];
            [self setValue: 0 animated: YES];
        }
    }
    

    Implement it like this:

    [self setSlider:[[Slider alloc] initWithFrame:CGRectMake(645, 25, 120, 50)]];
    [[self view] addSubview:[self slider]];
    [[self view] bringSubviewToFront:[self slider]];
    [[self slider] setDelegate:self];
    

    Don't forget to implement the delegate method:

    - (void)slideEnd {
        // Things you want to do when slide ends
    }