我正在尝试在UILabel
中显示计时器的计数。计时器工作正常,但我无法更新标签。在 Class1 中将NSTimer
设置为这样。
- (void)startTimer {
int timerCount = 5;
timer = [NSTimer scheduledTimerWithTimeInterval:4.0
target:self
selector:@selector(timerDecrement)
userInfo:nil
repeats:YES];
[timer fire];
}
- (void)timerDecrement {
Class2 *cls2 = [[Class2 alloc] init];
timerCount = timerCount-1;
[cls2 updateTimeLeftLabel];
}
+ (int)getTimerCount {
return timerCount;
}
在 Class2 :
中- (void)viewDidLoad {
if (timeLeftLabel == nil) {
timeLeftLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 70, 120, 30)];
timeLeftLabel.text = @"Time left";
[self.view addSubview:timeLeftLabel];
}
- (void)updateTimeLeftLabel {
NSLog(@"%@", [NSString stringWithFormat:@"%i",
[Class1 getTimerCount]]);
timeLeftLabel.text = [NSString stringWithFormat:@"Time left: %i",
[Class1 getTimerCount]];
}
记录了正确的计时器值,但UILabel
根本没有更新。怎么了?
答案 0 :(得分:1)
尝试将timerCount
作为您班级的@property
或static
。
答案 1 :(得分:1)
您创建Class2
的新实例,但不显示它。您应该在某处存储Class2
的实例并使用它。
答案 2 :(得分:1)
您只需将剩余时间传递给更新UILabel
作为参数的方法:
- (void)updateTimeLeftLabel:(NSInteger)timeLeft {
timeLeftLabel.text = [NSString stringWithFormat:@"Time left: %i",
timeLeft];
}
- (void)timerDecrement {
Class2 *cls2 = [[Class2 alloc] init];
timerCount = timerCount-1;
[cls2 updateTimeLeftLabel:timerCount];
}
答案 3 :(得分:1)
我需要更新我的UIButton的计数,所以我这样做了
-(void)viewDidLoad {
self.myLeagueTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}
- (int)timeIndervalRemain {
NSDate *currentTime = [NSDate date];
return (TIME_INTERVAL - [currentTime timeIntervalSinceDate:self.startTime]);
}
-(void) updateCountdown {
if ([self timeIndervalRemain] > 0) {
self.title = [NSString stringWithFormat:@"%d", [self timeIndervalRemain]];
} else {
[self timeExpire];
}
}
-(void) timeExpire {
if (_myLeagueTimer) {
[_myLeagueTimer invalidate];
_myLeagueTimer = nil;
}
}