2012年9月26日 星期三

NSTimer基本使用

一個Timer倒數計時,有暫停及重置功能,供Timer基本功能測試
Xcode版本4.5 & IOS6

1. 開一個新專案

2. 基本檔案列表

3. StoryBoard Layout

4. timerViewController.h基本變數及元件設定
#import <UIKit/UIKit.h>

@interface timerViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *timerLabel;
@property (weak, nonatomic) IBOutlet UIButton *countDownButton;
@property (weak, nonatomic) IBOutlet UIButton *resetButton;

@property (nonatomic) NSTimer  *timer;

@property (nonatomic) int  min;
@property (nonatomic) int  sec;
@property (nonatomic) int  minSec;

@property (nonatomic) int  nowTime;
@property (nonatomic) int  lastTime;

@end

5. timerViewController.m主程式碼設計
#import "timerViewController.h"

@interface timerViewController ()

@end

#define CountDownTime  10000

#define TimeUnin  0.01   // 0.01 sec

@implementation timerViewController

@synthesize timerLabel;
@synthesize countDownButton;
@synthesize timer;
@synthesize min;
@synthesize sec;
@synthesize minSec;

@synthesize nowTime;
@synthesize lastTime;

BOOL isRunning = NO;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
   
    lastTime = CountDownTime;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)countDown:(id)sender {
    if (isRunning == NO) {
       
        isRunning = YES;
       
        [self init_timer];
       
        [countDownButton setTitle:@"暫停" forState:UIControlStateNormal];
       
       
    }
    else {
       
        isRunning = NO;
       
        lastTime = nowTime;
       
        [timer invalidate];
       
        timer = nil;
       
        [countDownButton setTitle:@"計數" forState:UIControlStateNormal];
       
       
    }
   
}

- (void) showNowTime
{
    min = nowTime  / 6000;
    sec = (nowTime % 6000) /100 ;
   
    minSec = nowTime %100;
   
    timerLabel.text =   [NSString stringWithFormat:@"%02d:%02d:%02d", min, sec, minSec];

}


- (void) init_timer
{
   
    nowTime = lastTime;
   
    timer = [NSTimer scheduledTimerWithTimeInterval:TimeUnin target:self selector:@selector(GameTimer_Count) userInfo:nil repeats:YES];
   
}

- (void)GameTimer_Count {
   
    if (nowTime > 0)
    {
        nowTime-- ;
       
        [self showNowTime];
       
    }
    else
        nowTime = CountDownTime;
}
- (IBAction)reset:(id)sender {

    lastTime = CountDownTime;
   
    [countDownButton setTitle:@"倒數計數" forState:UIControlStateNormal];
   
   
    [timer invalidate];
   
    timer = nil;
   
    isRunning = NO;
   
    nowTime = lastTime;
   
    [self showNowTime];
   
   
}

6. 結果圖,分別表示,起始/啟動/暫停狀態



2 則留言:

Richard 提到...

hi 你好~
我目前正在學xcode,我一直有在follow你有關xcode的tutorials。

想按照你提供的方法去做,不過怎麼試都是不出來,我想在我的app的某些頁面上放上counter去計算使用者停留在這些頁面的時間,然後把停留時間最長的那一頁挑出來。不知道可否請你教我要如何implementation。



kirenenko.tw 提到...

實作上應該不難,主在在頁面切換後,原有頁面的計時器要停掉,並將時間記錄在一個公共變數,每個頁面都必須有一個記錄,這樣每次切換後,就去比較原有的時間記錄,找出時間最長的頁面。