iOS NSTimer範例demo

來源:互聯網
上載者:User

標籤:

所有代碼如下:是一個畫板三基顏色的隨機變化

#import "AppDelegate.h"@interface AppDelegate (){    NSTimer *_timer;//定時器}@end@implementation AppDelegate- (void)dealloc {    self.window =nil;    [super dealloc];}- (void)creatButton {    NSArray *arr = @[@"開始",@"暫停"];        for (NSInteger i = 0; i < arr.count; i++) {        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];        //會算座標        button.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/2-50, 100+i*60, 100, 50);        //設定標題        [button setTitle:arr[i] forState:UIControlStateNormal];                //增加事件 self 執行帶參數的btnClick:        //誰在增加的事件 那麼參數傳得就是誰        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];        //設定tag 值區分按鈕        button.tag = 1+i;                //粘貼        [self.window addSubview:button];            }}-(void)btnClick:(UIButton *)btn{    switch (btn.tag) {        case 1:        {            //啟動定時器            [_timer setFireDate:[NSDate distantPast]];        }            break;        case 2://定時器暫停        {            [_timer setFireDate:[NSDate distantFuture]];        }            break;                    default:            break;    }    }//button觸發之後調用的方法- (void)creatTimer {    /*     第一個參數:時間間隔 單位 s       2     : 目標對象地址 (任意) 一般寫self       3     :目標對象的行為 選取器        4    : nil        5    : YES 是否重複     一旦用這個函數建立定時器 那麼定時器就會立即啟動     定時器啟動之後 就會起一個子線程 每個一段時間 通知 UI主線程 使self 調用 timerClick 方法     */    //執行個體化一個定時器對象        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerClick) userInfo:nil repeats:YES];    //預設建立 NSTimer 之後就會啟動        //但是我們的需求 點擊按鈕才能啟動    //現在我們應該先把定時器暫停了        //暫停定時器    [_timer setFireDate:[NSDate distantFuture]];        }//定時器 觸發的函數- (void)timerClick {    //NSLog(@"%s",__func__);//    //    CGFloat red = arc4random()%256/255.0;//隨機產生 0--1//    CGFloat green = arc4random()%256/255.0;//    CGFloat blue = arc4random()%256/255.0;//           //通過三基色進行配色    //0-1    self.window.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];}- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];        [self creatButton];    //建立定時器    [self creatTimer];                self.window.backgroundColor = [UIColor whiteColor];    [self.window makeKeyAndVisible];    return YES;}- (void)applicationWillResignActive:(UIApplication *)application {    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.}- (void)applicationDidEnterBackground:(UIApplication *)application {    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.}- (void)applicationWillEnterForeground:(UIApplication *)application {    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.}- (void)applicationDidBecomeActive:(UIApplication *)application {    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.}- (void)applicationWillTerminate:(UIApplication *)application {    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.}@end


iOS NSTimer範例demo

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.