how to stop repeat timer? - objective-c

I am a beginner when it comes to iOS App development. I want to move a label from left to right until it reaches half the screen width - i.e. the label should move by 240px (the label moves left to right like a marquee).
I have used NSTimer and I want to stop the timer when the label reaches half the view's width.
I have used the following code but it moves the label out of the view:
- (void)viewDidLoad {
[super viewDidLoad];
timer = [[NSTimer scheduledTimerWithTimeInterval:0.09 target:self selector:#selector(time:) userInfo:nil repeats:YES] retain];
}
- (void)time:(NSTimer *)theTimer {
label.center = CGPointMake(label.center.x+3.5, label.center.y);
NSLog(#"point:%#", label);
if (label.center.x < - (label.bounds.size.width/2)) {
label.center = CGPointMake(320+(label.bounds.size.width/2), label.center.y);
}
}
How can I solve this, please?

If you want to stop the repeating timer, you can use
if (/*You label is in position*/)
[myTimer invalidate];
But that's not the normal way to do animation in iOS, try this instead:
CGRect endFrame = /*The frame of your label in end position*/
[UIView animateWithDuration:0.5 animations:^{ myLabel.frame = endFrame;}];

To stop a timer, do [timer invalidate].
You can't "pause" a timer, so once you do this you'll need to call another timer.

correct way to invalidate your timer is
[myTimer invalidate];
myTimer = nil;

Related

Use for loop with UIAnimation in Objective C

I want to show number in a UILabel from an unknown number to unknown number. Suppose from 40 to 699. I want to show this one by one and then break the loop sequence when required number is arrived.
E.g {40,41,42...667,668,669}
I want to remove the previous number from the label and add new number to the label object.
I am confuse to use UIAnimation in for() Loop.
Does anyone have any idea how to do this?
Using timer to animation with increase counter.
int loopCount;
NSTimer *myTimer;
// Method that calls your timer.
- (void)doStuff {
loopCount++;.
self.yourLabel.alpha = 0;
[UIView animateWithDuration:0.65 delay:0 options:UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse animations:^{
self.yourLabel.alpha = 1;
} completion:nil];
if (loopCount >= 669) {
[myTimer invalidate];
myTimer = nil;
self.yourLabel.alpha = 0;
}
}
// Method that kicks it all off
- (IBAction)startDoingStuff {
myTimer = [NSTimer scheduledTimerWithTimeInterval:0.75
target:self
selector:#selector(doStuff)
userInfo:nil
repeats:YES];
}

Objective c : How to set time and progress of uiprogressview dynamically?

Say I have a UIProgressBar with size (394,129,328,9) and I increased the height with
CGAffineTransform transform = CGAffineTransformMakeScale(1.0f, 3.0f);
PgView.transform = transform;
What I need to implement is : If I have 5 minute time,the progressView should be filled with a certain amount and totally filled at the end of 5 minute. Same for 1 minute and 30 minutes too.
I am implementing like this :
-(void)viewWillAppear:(BOOL)animated
{
CGAffineTransform transform = CGAffineTransformMakeScale(1.0f, 3.0f);
PgView.transform = transform;
recievedData = 0.01;
xpectedTotalSize = 1.0;
PgView.progress = 0.0;
[self performSelectorOnMainThread:#selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO];
}
- (void)makeMyProgressBarMoving
{
float actual = [PgView progress];
if (actual < 1)
{
PgView.progress = actual + ((float)recievedData/(float)xpectedTotalSize);
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(makeMyProgressBarMoving) userInfo:nil repeats:NO];
}
else{
}
}
And it works. But I want to implement progress and time interval dynamically? Any idea??
Thanks in advance.
It's difficult to understand your intention. As I suppose, you want to update the progress bar only if new values are available instead of updating with a fixed timer interval.
This would result in the simple answer: update your progress bar whenever you change the value of 'recievedData'. So, the method 'makeMyProgressBarMoving' doesn't need a timer. Also, you don't need to remember the 'actual' value. You can directly assign the 'receivedData/xpectedTotalSize' to the progress bar.
- (void) updateProgressBar
{
PgView.progress = ((float)receivedData/(float)xpectedTotalSize);
}
- (void) updateReceivedData
{
if (receivedData < 20)
receivedData += 1.0;
else
receivedData += 10.0;
[self updateProgressBar];
}
-(void)viewWillAppear:(BOOL)animated
{
receivedData = 0.0;
xpectedTotalSize = 100.0;
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(updateReceivedData) userInfo:nil repeats:YES];
}
Now, a timer is still used for demonstration to call 'updateReceivedData' which just increments 'receivedData' and calls 'updateProgressBar'. As you see, 'updateReceivedData' does not increment linear, again just for demonstration. If 'updateReceivedData' would be called on demand instead by the timer then also the progress bar would be updated on demand. Now it's just an issue of how and when you want to update your receivedData. It's not an issue regarding progress bars.

Press and hold to make Image move

I have a button and an image. When the button is pressed and held I want the image to movie across the screen quickly. Right now after I press and hold it just moves after I let go. I need it to start moving after a certain amount of time and stop when I let go.
here is what I have:
- (IBAction)buttonDown:(id)sender
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
x = x + 100;
}
With below code, you have to push 3 seconds to move _imageView, and then the image begins moving, and when you release the button, the image stops.
- (IBAction)pushToMove:(id)sender {
[self performSelector:#selector(move) withObject:nil afterDelay:3.0];
}
- (void)move
{
_nt = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:#selector(goRight)
userInfo:nil
repeats:YES];
}
- (void)goRight
{
_imageView.frame = CGRectMake(_imageView.frame.origin.x + 10, _imageView.frame.origin.y,
_imageView.frame.size.width, _imageView.frame.size.height);
}
- (IBAction)stop
{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:#selector(move) object:nil];
[_nt invalidate];
}
I put this sample project to GitHub. You can download and just run it.
https://github.com/weed/p120804_ImageMoveDuringPushButton
This can be done in interface builder by simply liking to the buttons touch down property instead of touch up inside. In code it looks like this:
[myButton addTarget:self action:#selector(myMethod) forControlEvents:UIControlEventTouchDown];
In addition to this, you'll want to do some state checking on your animation, and use UIViewAnimationOptionBeginFromCurrentState as an option to help it pick up where it left off when the user presses the button again.

How to flash a button on UI thread?

I have a button on my UI that I would like to flash (turn on and then off again) every 800ms, once the button has been pressed. I do that with the following code:
- (void)flickEmergencyButton {
// Check whether an emergency is in progress...
if (model.emergencyInProgress) {
// ...and if so, flick the state
self.emergencyButton.selected = !self.emergencyButton.selected;
// Make this method be called again in 800ms
[self performSelector:#selector(flickEmergencyButton) withObject:nil afterDelay:0.8];
} else {
// ...otherwise, turn the button off
self.emergencyButton.selected = NO;
}
}
...which works really well, except: There is a UIScrollView on the UI as well and while the user has his finger down on it and is scrolling around, the button freezes. While I completely understand why that is, I am not sure what to do about it.
The performSelector:withObject:afterDelay message schedules the message to be send on the current thread, which is the main thread, ie. the UI tread and hence does not get to process the message until all other UI activity has come to an end. Correct? But I need to do this on the UI thread as I cannot select/un-select the button on any other thread, right? So what is the solution here?
I would recommend using Core Animation. Try something like this:
-(void) flash{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3f];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
if( emergency ){
// Start flashing
[UIView setAnimationRepeatCount:1000];
[UIView setAnimationRepeatAutoreverses:YES];
[btn setAlpha:0.0f];
}else{
// Stop flashing
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationRepeatCount:1];
[btn setAlpha:1.0f];
}
emergency = !emergency;
[UIView commitAnimations];
}
Where btn is declared as
#property(nonatomic, retain) IBOutlet UIButton *btn;
and emergency is a simple BOOL variable.
Call flash to start and to stop the animation.
In this example we animate the alpha attribute for simplicity, but you can do the same with the button backcolor, as Sam said in his answer, or whatever attribute you like.
Hope it helps.
UPDATE:
Regarding making the transition between two images, try calling imageFlash instead of flash:
-(void) imageFlash{
CABasicAnimation *imageAnimation = [CABasicAnimation animationWithKeyPath:#"contents"];
[btn setImage:normalState forState:UIControlStateNormal];
if( emergency ){
imageAnimation.duration = 0.5f;
imageAnimation.repeatCount = 1000;
}else{
imageAnimation.repeatCount = 1;
}
imageAnimation.fromValue = (id)normalState.CGImage;
imageAnimation.toValue = (id)emergencyState.CGImage;
[btn.imageView.layer addAnimation:imageAnimation forKey:#"animateContents"];
[btn setImage:normalState forState:UIControlStateNormal]; // Depending on what image you want after the animation.
emergency = !emergency;
}
Where normalState and emergencyState are the images you want to use:
Declared as:
UIImage *normalState;
UIImage *emergencyState;
Assigning the images:
normalState = [UIImage imageNamed:#"normal.png"];
emergencyState = [UIImage imageNamed:#"alert.png"];
Good luck!
While this feels like a job for CoreAnimation (perhaps animating the backgroundColor of a custom UIControl) you could accomplish this with an NSTimer running in the appropriate run loop mode.
e.x.
NSTimer *timer = [NSTimer timerWithTimeInterval:0.8f target:self selector:#selector(flicker:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
and when you want to stop animation:
[timer invalidate], timer = nil;
button.selected = NO;
By adding the timer to all NSRunLoopCommonModes, you not only add it to the default run loop mode but the mode it is in while user interaction is being continuously processed (UITrackingRunLoopMode.)
Apple's docs give a more thorough explanation of run loop modes and run loops in general.

NSTimer questions

So I have two problems but both are related.
I created a "animation" that moves a progress view when a button is clicked by using NSTimer. This animation works fine the first couple times the button is clicked but after that it starts speeding up the process, practically skipping from the initial start of the NSTimer loop to the end of the NSTimer loop. I was wondering if anyone has ever heard of this issue and/or knows a solution?
I created the same thing in question 1 but in a UItableViewCell and the NSTimer loop is activated when the edit button is pressed. The edit button activates a function that has this [self.tableView2 setEditing:NO animated:YES]; and the NSTimer scheduledTimerWithInterval ... (The progress view animation). The issue here is that it the setEdit animation no longer animates it just pops into place. Once again, does anyone know of a solution for this?
Here is the code for question 2 (Both the code for the questions are very similar so if you can spot the problem here then it is likely I can use that solution to fix them both):
-(void)editTable{
[self.tableView2 setEditing:YES animated:YES];
iCount = 8;
iCount2 = 257;
forwardProgress = YES;
animationFlag = YES;
myTimer = [NSTimer scheduledTimerWithTimeInterval:0.001f target:self selector:#selector(increaseAmount) userInfo:nil repeats:YES];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(cancelEdit)];
}
-(void)cancelEdit{
[self.tableView2 setEditing:NO animated:YES];
forwardProgress = NO;
animationFlag = YES;
iCount = 38;
iCount2 = 227;
myTimer = [NSTimer scheduledTimerWithTimeInterval:0.001f target:self selector:#selector(increaseAmount) userInfo:nil repeats:YES];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:#selector(editTable)];
}
-(void)increaseAmount{
float max = 38.0f;
float max2 = 257.0f;
float min2 = 227.0f;
float min = 8.0f;
if (animationFlag == YES) {
if (forwardProgress == YES) {
if (iCount <= max) {
iCount++;
// NSLog(#"iCount = %i", iCount);
}
if (iCount2 >= min2) {
iCount2--;
// NSLog(#"iCount2 = %i", iCount2);
}
if (iCount <= max) {
[tableView2 reloadData];
}
if (iCount2 >= min2) {
[tableView2 reloadData];
}
if (iCount == max) {
animationFlag = NO;
}
newFrame = CGRectMake(iCount, 33.0f, iCount2, 11.0f);
[tableView2 reloadData];
}else{
if (iCount >= min) {
iCount--;
NSLog(#"iCount = %i", iCount);
}
if (iCount2 <= max2) {
iCount2++;
NSLog(#"iCount2 = %i", iCount2);
}
newFrame = CGRectMake(iCount, 33.0f, iCount2, 11.0f);
if (iCount >= min) {
[tableView2 reloadData];
}
if (iCount2 <= max2) {
[tableView2 reloadData];
}
if (iCount == min) {
animationFlag = NO;
}
}
}
}
Any timer invalidates itself when it has finished unless it has repeats:YES. If that's the case, you need to invalidate it yourself at some point, ideally when all your conditions are met. In your case I think you'd want it when you're setting animationFlag == 0 (I presume that's when you want the timer to stop firing). Use something like this:
if ([myTimer isValid]) {
[myTimer invalidate];
myTimer = nil;
You also need to place that code in editTable at the beginning. That way, if a timer was running and someone started it again, it would first reset, and then begin again.Otherwise you have multiple timers all firing increaseAmount. You also need it anytime the user cancels the timer.
You probably have to invalidate the timer from your first animation. I suspect that you have two timers running and therefore the speed of the animation is doubled.
This is probably because of the reloadData call in your timer callback. A tableview cannot reload and animate at the same time.
I believe rgeorge is correct;
You don't get rid of the "myTimer" when you stop your animation. So even though you may not see the animation any more, increaseAmount is still being called over and over. Change the method to something like this:
-(void)increaseAmount:(NSTimer*)Timer;
Then, when you're done with increase amount, make sure to turn off the timer from within increaseAmount.