通过segue

时间:2015-07-05 22:17:56

标签: ios objective-c nstimer

我有一个小样本项目,我用它来弄清楚如何在我的主项目中实现它。这个简单的项目有2个VC,彼此之间有segue。

在初始VC上是一个通向TimerVC的按钮(两者都使用相同的类)。

TimerVC有一个按钮和一个标签。按下按钮时,标签将每秒增加1。

如果定时器打开并且我转回初始VC然后转到TimerVC,定时器继续,但标签停止更新。

如何更新标签?计时器继续在后端进行,但一旦发生segue,标签就会停止更新。

编辑:下面提供的代码。定时器也更复杂,可以代表我尝试做的一些事情。

VC.H

NSTimer * timer;

NSTimer * updateTimer;

@property (weak, nonatomic) IBOutlet UIButton *idleOutler;

- (IBAction)idleAttack:(id)sender;

VC.M

int enemy001Hp = 100;

int deadEnemy = NO;
int noHealth = 0;

bool enemy001Active = NO;

- (void) enemy1 {
enemy001Active = YES;
self.enemyHpLabel.text = [NSString stringWithFormat:@"%i", enemy001Hp];
}


- (void) enemyDamageTimer {
if (enemy001Active == YES) {
    enemy001Hp -= 50;
    self.enemyHpLabel.text = [NSString stringWithFormat:@"%i",enemy001Hp];
  }
}

- (void) updateLabelTimer {
if (enemy001Active == YES) {
    self.enemyHpLabel.text = [NSString stringWithFormat:@"%i", enemy001Hp];
} 
}

- (void) stopTimer {
[timer invalidate];
timer = nil;
self.enemyHpLabel.text = [NSString stringWithFormat:@"0"];
}

- (void)viewDidLoad {
[super viewDidLoad];
[self enemy1];
if (enemy001Active) {
    self.enemyHpLabel.text = [NSString stringWithFormat:@"%i", enemy001Hp];
} else if (enemy002Active == YES) {
    self.enemyHpLabel.text = [NSString stringWithFormat:@"%i", enemy002Hp];

}
}

- (IBAction)idleAttack:(id)sender {
idleOn = YES;
self.idleOutler.hidden = YES;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(enemyDamageTimer) userInfo:nil repeats:YES];
 updateTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateLabelTimer) userInfo:nil repeats:YES];
if (enemy001Active == YES) {
    if (enemy001Hp <= 0) {
        [self enemy2];
        enemy001Active = NO;
        enemy002Active = YES;
    }
} else if (enemy002Active == YES) {
    if (enemy002Hp <= 0) {
        self.enemyHpLabel.text = [NSString stringWithFormat:@"0"];
        enemy002Hp = 0;
        enemy002Active = NO;
        [self stopTimer];
    }
}
} 

0 个答案:

没有答案