简体   繁体   中英

Update UILabel continuously — Objective-c

I'm trying to display the count of a timer in a UILabel . The timer works fine but I'm not able to update the label. The NSTimer is set up like this in Class1 .

- (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;
}

In 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]];
}

The correct timer value is logged but the UILabel isn't updated at all. What's wrong?

尽量让timerCount@property类或static

You create a new instance of the Class2 and do not present it. You should store instance of Class2 somewhere and work with it.

You can simply pass the time left to the method updating the UILabel as a parameter:

- (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];
}

I needed to update count on my UIButton so i have done like this

    -(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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM