我有两个 View Controller ,都通过 Segue 连接并使用 Storyboard。
在 View Controller 1 中,我有一个 NSTimer 计数并更新一个 UILabel。
当我切换到 View Controller 2 并返回到 View Controller 1 时,uilabel 不再更新。
这是一些代码:
headerfile
NSString *timerTicksForCounter;
- (void)viewDidLoad
{
[super viewDidLoad];
[self updateTimerLabel];
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self updateTimerLabel];
}
- (void) startLastConUpdater
{
lastCTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(updateTimer)
userInfo:nil
repeats:YES];
}
-(void) updateTimerLabel
{
NSLog(@"timer: %@", timerTicksForCounter);
if (timerTicksForCounter) {
NSLog(@"timer not null");
mainTimerLabel.text = timerTicksForCounter;
}
}
- (void)updateTimer
{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:stopDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm:ss"];
timerTicksForCounter = [dateFormatter stringFromDate:timerDate];
[self updateTimerLabel];
}
最佳答案
不再更新是什么意思?这是否意味着您丢失了切换前显示的内容或不再更新。如果它不再更新,那是因为您没有以适当的方法启动计时器。你可以这样做:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self startLastConUpdater];
}
这应该可以解决我上面提到的两个问题。
关于ios - 切换 UIViewControllers 后停止使用 NSTimer 更新 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23558795/