1. 程式人生 > >iOS第四課 NSTimer定時器

iOS第四課 NSTimer定時器

可以在每隔固定時間傳送一個訊息
通過此訊息來呼叫相應的時間函式
通過此函式可在固定時間段來完成一個根據時間間隔的人物

    UIButton* btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame=CGRectMake(100, 100, 80, 40);
    [btn setTitle:@"啟動定時器" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(pressStart) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    UIButton* btnStop=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnStop.frame=CGRectMake(100, 150, 80, 40);
    [btnStop setTitle:@"停止定時器" forState:UIControlStateNormal];
    [btnStop addTarget:self action:@selector(pressStop) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnStop];
    
    UIView* view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
    view.backgroundColor=[UIColor orangeColor];
    view.tag=103;
    [self.view addSubview:view];

建立並開始定時器函式

-(void) pressStart
{
    //NSTimer的類方法建立一個定時器並啟動這個定時器
    //p1:每個多長時間呼叫定時器函式,以秒為單位
    //p2:表示實現定時器的函式的物件
    //p3:定時器函式物件
    //p4:可以傳入定時器裡的一個引數,
    //p5:定時器是否重複 YES為重複
    //返回一個新建好的定時器物件
    _timerView=[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(uploadTimer:) userInfo:@"小明" repeats:YES];
    
}

停止函式

-(void) pressStop
{
    
    if (_timerView!=nil) {
        //停止計時器
        [_timerView invalidate];
    }
    
}

定時器函式 移動view

//定時器函式
-(void) uploadTimer:(NSTimer*) timer
{
    NSLog(@"test......name=%@",timer.userInfo);
    UIView* view=[self.view viewWithTag:103];
    view.frame=CGRectMake(view.frame.origin.x+5, view.frame.origin.y+5, 80, 80);
    
}

在這裡插入圖片描述