jsetting32
jsetting32

Reputation: 1632

Scroll UISlider Automatically

So currently I have a UISlider in a UIViewcontroller that is meant to start animations within subviews when the user slides.. Basically when the user slides I have this battery with a filling in it that fills the empty battery image with a bar to indicate power within a cell, and the user can slide to see the energy the battery has at certain times of the day.

At the moment, when the View loads I would like the UISlider to AUTOMATICALLY start sliding from the beginning of the slider and scroll to the end within, lets say 5 seconds.

I implemented a loop that cycles through all the values of the uislider using this loop

for (int i = 0; i < [anObject count] - 2; i++)
{
    sleep(.25);
    NSUInteger index = (NSUInteger)(slider.value + 0.5); // Round the number.
    [slider setValue:index animated:YES];
}

[anObject count] - 2 is equal to 62 at this time of day but will change and increment every 15 seconds because I'm fetching data from a server.

But that aside, why doesn't this work? The loop?

EDIT:

So heres what I did with NSTIMER

[NSTimer timerWithTimeInterval:0.25 target:self selector:@selector(animateSlider) userInfo:nil repeats:NO];

and animateSlider looks like this:

- (void)animateSlider:(NSTimer *)timer
{
    NSLog(@"Animating");
    NSUInteger index = (NSUInteger)(slider.value + 0.5); // Round the number.
    [slider setValue:index animated:YES];
}

But no luck... Why isn't NSTimer "firing"..... I remmeber vaguely there was a method that FIRES an nstimer method but not sure if that's needed...

EDIT:

Ahh it does need "Fire"....

NSTimer *timer = [NSTimer timerWithTimeInterval:0.25 target:self selector:@selector(animateSlider) userInfo:nil repeats:NO];
[timer fire];

But for some reason it only fires once.... Any ideas ?

Upvotes: 1

Views: 806

Answers (1)

Michael Dautermann
Michael Dautermann

Reputation: 89509

"for some reason it only fires once..."

If you changed the NSTimer set up to this:

NSTimer *timer = 
   [NSTimer scheduledTimerWithTimeInterval:0.25 
                                    target:self 
                                  selector:@selector(animateSlider:) 
                                  userInfo:nil 
                                   repeats:YES];

This would schedule the timer on the current run loop immediately.

And since the "repeats" parameter is "YES", you'd then repeat the timer every quarter second, until you invalidate the timer (which you should do when the ending condition is reached, like when the slider reaches its destination).

P.S. You'd need to change the selector method declaration of your timer's target slightly. According to Apple's documentation, "The selector must correspond to a method that returns void and takes a single argument. The timer passes itself as the argument to this method."

So declare "animateSlider" like this instead:

- (void)animateSlider: (NSTimer *) theTimer;

Upvotes: 2

Related Questions