NSTimer in iPhone

Introduction

In this article I will create a Single View application with a NSTimer Class to do animation. Using this class we set the frame just like a timer.To understand it we use the following.

Step 1

Open XCode by double-clicking on it.

Step 2

Create a new XCode Project by clicking on it.

Step 3

Now select Single View Application and click on Next.

Step 4

Now provide your Product Name and Company Identifier.

Step 5

Select the location where you want to save your project and click on Create.

Step 6

Now we write the code.

ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController{
NSTimer *Timer;
}
@end


ViewController.m

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CGRect RectFrame;
RectFrame.origin.x = 25;
RectFrame.origin.y = 300;
RectFrame.size.width = 20;
RectFrame.size.height = 20;
for(int i = 0; i < 10; i++)
{
UIView *myView = [[UIView alloc] initWithFrame:RectFrame];
[myView setTag:i];
[myView setBackgroundColor:[UIColor blueColor]];
RectFrame.origin.x = RectFrame.origin.x + RectFrame.size.width + 10;
[self.view addSubview:myView];
}
Timer = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(moveRect) userInfo:nil repeats:YES];
}
-(void)moveRect
{
int r = rand() % 10;
for(UIView *aView in [self.view subviews])
{
if([aView tag] == r)
{
int movement = rand() % 100;
CGRect RectFrame = aView.frame;
RectFrame.origin.y = RectFrame.origin.y - movement;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:.2];
[aView setFrame:RectFrame];
[UIView commitAnimations];
if(RectFrame.origin.y < 0)
{
[Timer invalidate];
}
}
}
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end

Step 7

Finally we click on the Run button to show the output.

Step 8

Output1 in iPhone:

Output1-in-iPhone.png

Output2 in iPhone:

Output2-in-iPhone.png

Output3 in iPhone:

Output3-in-iPhone.png

Output4 in iPhone:

Output4-in-iPhone.png


Similar Articles