NSTimer定時器、視圖對象的移動

定時器寫在視圖控制器ViewController類中:

  • ViewController.h
//定義一個定時器對象
//可以在固定時間發(fā)送一個消息
//通過此消息來調(diào)用相應的時間函數(shù)方法
@property(strong,nonatomic)NSTimer *timerView;
  • 以按鈕點擊控制定時器開始和結(jié)束為例
  • ViewController.m
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //創(chuàng)建一個普通按鈕
    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];
    
    //同理設置結(jié)束按鈕
    UIButton *btnStop = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnStop.frame = CGRectMake(100, 200, 80, 40);
    [btnStop setTitle:@"停止定時器" forState:UIControlStateNormal];
    
    [btnStop addTarget:self action:@selector(pressStop) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btnStop];
}
  • 然后編寫啟動和停止事件:
//ViewController.m
//啟動按鈕響應事件
-(void)pressStart{
    //NSTimer的類方法創(chuàng)建一個定時器并且啟動這個定時器
    //P1:每隔多久調(diào)用定時器函數(shù)
    //P2:調(diào)用定時器函數(shù)的對象
    //P3:定時器函數(shù)對象
    //P4:可以傳入定時器函數(shù)中一個參數(shù),沒有參數(shù)時寫nil
    //P5;定時器是否重復操作 YES重復 NO只調(diào)用一次
    //返回值是一個新建的定時器對象
    _timerView = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTimer:) userInfo:@"lychee" repeats:YES];
}
//定時器函數(shù)
//可以將定時器本身作為參數(shù)傳入
-(void)updateTimer:(NSTimer *)timer{
    NSLog(@"TEST!!!name=%@",timer.userInfo);
}
//停止按鈕響應事件
-(void)pressStop{
    if(_timerView!=nil){
        [_timerView invalidate];
    }
}

根據(jù)定時器移動視圖對象

  • 在ViewController.m中,viewDidLoad中添加UIView控件
UIView *view = [[UIView alloc]init];
view.frame = CGRectMake(0, 0, 80, 80);
view.backgroundColor = [UIColor orangeColor];
[self.view addSubview:view];
    
view.tag = 101;
  • 然后在定時器函數(shù)中移動視圖對象
//獲取界面中的UIView控件
UIView *view = [self.view viewWithTag:101];
view.frame = CGRectMake(view.frame.origin.x+1, view.frame.origin.y+1, view.frame.size.height, view.frame.size.width);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容