很简单的NSTimer例子
2011-10-21 17:16 Paul Wong 阅读(1561) 评论(0) 编辑 收藏 举报NSTimer就如.net的Timer一样,是一个时钟。
-(void)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 yellowColor]];
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];
}
}
}
}
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 yellowColor]];
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];
}
}
}
}