持续更新UILabel - Objective-c

时间:2013-12-27 11:24:23

标签: ios objective-c timer uilabel nstimer

我正在尝试在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根本没有更新。怎么了?

4 个答案:

答案 0 :(得分:1)

尝试将timerCount作为您班级的@propertystatic

答案 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;
    }
}