IOS-UITimer的使用

UITimer 是 iOS 系統(tǒng)中的定時器。

今天主要實現(xiàn)的功能點 開始/停止 定時器,給定時器刷新函數(shù)帶入?yún)?shù)和如何通過定時器更改 View 的位置屬性,從而得到 View 的動畫效果。

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

{
    // 定義一個定時器
    NSTimer* _timerView;
}

@property (retain, nonatomic) NSTimer* timerView;

@end

接著我們在 ViewController.m 編寫如下代碼

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

// 屬性和成員變量的同步
@synthesize timerView = _timerView;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    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* btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn1.frame = CGRectMake(100, 200, 80, 40);
    [btn1 setTitle:@"停止定時器" forState:UIControlStateNormal];
    [btn1 addTarget:self action:@selector(pressStop) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn1];

    UIView* view = [[UIView alloc] init];
    view.frame = CGRectMake(0, 0, 50, 50);
    view.backgroundColor = [UIColor greenColor];
    view.tag = 200;
    [self.view addSubview:view];
}

- (void) pressStart {
    // P1 每隔多久調(diào)用定時器,以秒為單位
    // P2 實現(xiàn)定時器函數(shù)的對象
    // P3 定時器函數(shù)對象
    // P4 可以定時器函數(shù)中的一個參數(shù),可以傳 nil
    // P5 是否重復(fù)
    _timerView = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTimer:) userInfo:@"DaveZ" repeats:YES];
    
    
}

- (void) pressStop {
    if (_timerView != nil) {
        [_timerView invalidate];
    }
}

// 可以將定時器本身作為參數(shù)傳入
- (void) updateTimer: (NSTimer*) timer {
    NSLog(@"TEST name = %@", timer.userInfo);
    
    UIView* view = [self.view viewWithTag:200];
    view.frame = CGRectMake(view.frame.origin.x + 1, view.frame.origin.y + 1, 50, 50);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,197評論 4 61
  • 現(xiàn)在的年輕人都在想些什么?我真是不懂了。大概我們真的老了。 那天去快遞公司寄快遞,填單子的時候,聽見幾個小姑娘的對...
    慕容小秋閱讀 617評論 0 0
  • 一、 人的一生何其短暫 從黑發(fā)到白發(fā),仿佛就一瞬間的事兒 到最后,帶不走任何東西 唯有那些刻骨銘心的記憶 在最后一...
    許17閱讀 470評論 2 7

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