我想创建一个按钮,将我带到另一个视图控制器并自动从3开始倒计时到0,但我不知道如何设置其他视图控制器的倒计时。这是我试过的代码:
@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 :(得分:0)
您必须将倒计时代码放在一个方法中,您应该使用viewDidLoad
或viewWillAppear
方法调用该方法。
@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