2014-02-15 69 views
0

我想創建一個按鈕,帶我到另一個視圖控制器,並自動開始從3到0的倒計時,但我不知道如何設置其他視圖控制器倒計時。這是我試過的代碼:自動啓動倒計時Xcode XIB

@implementation TestViewController 

-(IBAction)test:(id)sender { 
    CountdownViewController *cdvc = [[CountdownViewController alloc] 
initWithNibName:@"CountViewController" bundle:nil]; 
    [self.navigationController pushViewController:cdvc animated:YES]; 
} 

@implementation CountdownViewController 

int maintInt = 3; 
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES]; 

-(void)countDown { 
    maintInt -= 1; 
    count.text = [NSString stringWithFormat:@"%i", maintInt]; 
    if(maintInt==1){ 
     [timer invalidate]; 
    } 
} 
+0

你的代碼對我來說似乎還行。你遇到的問題究竟是什麼?倒計時視圖控制器中的 – Merlevede

+0

實際上它表示未聲明的標識符自身。我想我應該在其他地方添加int和nstimer,但我不知道在哪裏。 – Atlas

+0

行上的錯誤'int maintInt = 3;'?因爲如果是這樣的話,你不能在這樣的方法之外添加代碼。 –

回答

0

你必須把你的倒計時代碼的方法,你應該在viewDidLoadviewWillAppear方法調用關於您的需求。

@implementation TestViewController 

-(IBAction)test:(id)sender { 
    CountdownViewController *cdvc = [[CountdownViewController alloc] 
initWithNibName:@"CountViewController" bundle:nil]; 
    [self.navigationController pushViewController:cdvc animated:YES]; 
} 

@end 

@implementation CountdownViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    // .. customize your views here .. 

    // Initialize the timer once your view has been loaded. 
    // 
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown:) userInfo:nil repeats:YES]; 
} 


static int maintInt = 3; 

- (void)countDown:(NSTimer *)timer { 
    count.text = [NSString stringWithFormat:@"%i", maintInt]; 
    maintInt -= 1; 

    if (maintInt == 0 && timer) { 
     [timer invalidate]; 
     timer = nil; 
    } 
} 

@end