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 ?
"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;
Related
I'm working on a very simple iPhone game that involves choosing the right colored button as many times in a row based on a randomized voice prompt. I have it set up so that if the button is one color and gets clicked, it always goes to a hard-coded color every time (e.g. if you click red, it always turns blue). The color change method is set up in an IBOutlet. I have a timer set up in a while loop, and when the timer ends it checks if the player made the right selection. The problem is that the button color change does not occur until after the timer runs out, and this causes a problem with the method used to check the correct answer. Is there a way to make this color change happen instantly? From what I've searched I know it has something to do with storyboard actions not occurring until after code executes, but I haven't found anything with using a timer. Here is a section of the method that calls the timer if the answer is correct:
BOOL rightChoice = true;
int colorNum;
NSDate *startTime;
NSTimeInterval elapsed;
colorNum = [self randomizeNum:middle];
[self setTextLabel:colorNum];
while (rightChoice){
elapsed = 0.0;
startTime = [NSDate date];
while (elapsed < 2.0){
elapsed = [startTime timeIntervalSinceNow] * -1.0;
NSLog(#"elapsed time%f", elapsed);
}
rightChoice = [self correctChoice:middleStatus :colorNum];
colorNum = [self randomizeNum:middle];
}
One of two things stood out
You're using a while loop as a timer, don't do this - the operation is synchronous.
If this is run on the main thread, and you code doesn't return, your UI will update. The mantra goes: 'when you're not returning you're blocking.'
Cocoa has NSTimer which runs asynchronously - it is ideal here.
So let's get to grips with NSTimer (alternatively you can use GCD and save a queue to an ivar, but NSTimer seems the right way to go).
Make an ivar called timer_:
// Top of the .m file or in the .h
#interface ViewController () {
NSTimer *timer_;
}
#end
Make some start and stop functions. How you call these is up to you.
- (void)startTimer {
// If there's an existing timer, let's cancel it
if (timer_)
[timer_ invalidate];
// Start the timer
timer_ = [NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:#selector(onTimerFinish:)
userInfo:nil
repeats:NO];
}
- (void)onTimerFinish:(id)sender {
NSLog(#"Timer finished!");
// Clean up the timer
[timer_ invalidate];
timer_ = nil;
}
- (void)stopTimer {
if (!timer_)
return;
// Clean up the timer
[timer_ invalidate];
timer_ = nil;
}
And now
Put your timer test code in the onTimerFinish function.
Make an ivar that stores the current choice. Update this ivar when a choice is made and make the relevant changes to the UI. Call stopTimer if the stop condition is met.
In the onTimerFinished you can conditionally call and startTimer again if you desire.
Hope this helps!
I have an application in which I want that when I run my application initially it should show a screen for 2 seconds that displays warning about the app and just after 2 seconds a countdown should start from 5 seconds that should decrement from 5 second to 1 second.
There are two ways:
[NSTimer timerWithTimeInterval: .....]
[self performSelector: withObject: afterDelay:]
so if i got your point you want to display a warning screen and after 2 seconds you want to show the user count down start from 5 and end at 1 .. well this can done easy by using a timer and counter as following :
define a NSTimer and start it once the warning view is shown .. your definition will be like this:
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(timerFires) userInfo:nil repeats:YES];
[timer fire];
define a global integer and set its initial Value to 7 (lets suppose you name it counter).
-in timerFires selector you decreament counter by 1 and check its value when its equal to 5 start to show its vlaue on UILabel for example and when its 1 invalidate the timer and do you what you want at this point .. the timerFires will be like this:
- (void)timerFires
{
counter --;
if(counter ==5)
{
//show its Value
}
if(counter ==1)
{
[timer invalidate];
timer = nil;
//Do other stuff
}
}
[NSTimer scheduledTimerWithTimeInterval:60 target:self selector:#selector(updateFunction) userInfo:NULL repeats:YES];
In updateFunction you can write your code for count down.
You can also set "repeats:NO" and to call the updateFunction at the end of itself if it is necessary
I'm trying to develop a game and running into a small issue with NSTimer, once a sprite appear it has a certain amount on time in my scene before fading out.
double CALC_TIME = 5;
[NSTimer scheduledTimerWithTimeInterval:CALC_TIME target:self selector:#selector(hideSprite) userInfo:nil repeats:NO];
I want hideSprite to be called after 5 seconds, but instead it's called instantly(Or near instant).
A possible solution:
I know I could do this by setting the timer to repeat, and having a bool firstCall that is set first time and then the next interval the fading is done, the timer is invalidated but I don't think this is good practice
Like this:
bool firstCall = false;
-(void)hideSprite{
if(!firstCall){
firstCall = true
}else{
//fade out sprite
//Invalidate NSTimer
//firstCall = false;
}
}
Thanks for your help!
I suspect something else is calling hideSprite. The code you have written will cause the timer to wait for five seconds before calling the selector hideSprite.
Provide a different selector (write a new test method which just does an NSLog) to the timer and see what happens. This will tell you a) whether the timer is indeed immediately firing and b) if something else is calling hideSprite.
[NSTimer scheduledTimerWithTimeInterval:CALC_TIME target:self selector:#selector(testTimer) userInfo:nil repeats:NO];
-(void) testTimer { NSLog(#"Timer - and only the timer - called me."); }
-(void) hideSprite {
NSLog(#"I definitely wasn't called by the timer.");
}
Quite often it's easier to just use something like
[UIView animateWithDuration: 0 delay: 5 options:0 animations: nil completion:
^{
// fade sprite
}];
(not sure if animations can be nil, but you get the idea).
Consider initializing your timer using the initWithFireDate:interval:target:selector:userInfo:repeats method. Here is a more detailed look at NSTimer.
I have 4 images. I want to load image in first screen and change images after every 10 second. when we click any images than next screen come up.
please give me help i am new in iPhone.
Use NSTimer to trigger the image change. If the user taps an image and you want to stop the image rotation, you can invalidate the timer before switching to the next view.
You can try by creating a method that changes the image in the imageView and calling it using a NSTimer which repeatedly calls the method every 10 seconds.
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(changeImage) userInfo:nil repeats:YES];
- (void)changeImage {
// Change image here
}
HI Avinash,
I think you need below code...
******* IN VIEW DID LOAD
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(changeImage) userInfo:nil repeats:YES];
- (void)changeImage {
[self.imgview setImage:[UIImage imageNamed:#"test.png"]];
}
Thx
I have an int which defines the objectAtIndex, which gives it to the string, which then displays it in the UILabel, HOWEVER, when I modify the array (add a word to it in this case) when I have the UILabel go through the array it only displays the odd ones. I have done an NSLog and found out that it DOES PASS EVERY SINGLE THING to the string, but the Label isn't displaying every single one, it only does it the first time, then I modify the array, and it only does odd
edit: the code:
- (void) stuff {
NSArray *indivwords = [sentence componentsSeparatedByString:#" "];
count = [indivwords count]; //count=int
if (i < count) {
NSString *chunk = [indivwords objectAtIndex:i];
[word setText:chunk];
NSLog(chunk);
i++;
} else {
word.textColor = [UIColor greenColor];
[word setText:#"DONE"];
}
}
All of this is being controlled by an NSTimer, which sets it off based on a slider value. Also i is set to 0 in the IBAction
The IBAction code:
word.textColor = [UIColor whiteColor];
[timer invalidate];
i = 0;
speedd = (1/speed.value)*60;
timer = [NSTimer scheduledTimerWithTimeInterval:(speedd) target:self selector:#selector(stuff) userInfo:nil repeats:YES];
EDIT:
I fixed it! What I did was call this after i reached the count
-(void)stoptimer
{
[timer invalidate];
timer = [NSTimer scheduledTimerWithTimeInterval:(.01) target:self selector:#selector(empty) userInfo:nil repeats:YES];
}
empty is just a void with nothing in it, well, all I did was add a comment,
//don't look over here, nothing to see here, oh look at that
Somebody can close this if they want
You said the time interval of your NSTimer is controlled by a slider. Perhaps you are starting a new timer instance every time you change the slider value, so after a change you would have two timers running. The first one updates the label and increments i. The second one comes right after the first and finds i's value incremented, so it displays the next chunk instead of the current one.
Count the instances of your timer - NSLog the timer in the timer callback and compare the results - it may be that you're firing more than one.
My guess is that you have two different actions calling this method, when you think there should be one. I'd put a break point in there, and see if it stops where you think it should.