Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate UISlider smoothly

i want to animate an UISlider for e.g. 0.25 to 0.75 and back. This should show the user what is to do.

i tried this:

[self incrementCounter:[NSNumber numberWithInt:0]];


-(void) incrementCounter:(NSNumber *)i {
    [Slider setValue:[i floatValue]/1000];
    [self performSelector:@selector(incrementCounter:) withObject:[NSNumber numberWithInt:i.intValue+1] afterDelay:0.001];
}

but thats not so smooth... can i use transitions for this?

[Slider setValue:1 animated:YES];

is to fast...

[UIView animateWithDuration:2.0
                 animations:^{
                     [Slider setValue:0.2];
                 }];
[UIView animateWithDuration:2.0
                 animations:^{
                     [Slider setValue:0.5];
                 }];

Just animates the second one...

like image 808
Phil Avatar asked Dec 15 '12 17:12

Phil


2 Answers

You need to chain the animations by putting the second animation in the completion block of the first:

-(IBAction)animateSlider:(id)sender {

    [UIView animateWithDuration:2 animations:^{
        [self.slider setValue:.75];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:2 animations:^{
            [self.slider setValue:0.25];//or `[self.slider setValue:(.75)-(.5*finished)];` if you want to be safe
        }];
    }];
}
like image 190
rdelmar Avatar answered Oct 20 '22 13:10

rdelmar


Swift 2.2 version for rdelmar's answer

@IBOutlet weak var slider: UISlider!

func animateSlider(sender: AnyObject){
    UIView.animateWithDuration(2, animations:  {() in
        self.slider.setValue(0.75, animated: true)
        }, completion:{(Bool)  in
            UIView.animateWithDuration(2, animations: {() in
                self.slider.setValue(0.25, animated: true)
            })
    })
}

and to call the function pass the UISlider in the parameter

animateSlider(self.slider)
like image 39
Abdullah Saeed Avatar answered Oct 20 '22 13:10

Abdullah Saeed