Updating UILabel in the middle of a for() loop

后端 未结 3 1178
慢半拍i
慢半拍i 2020-12-05 21:39

I have a method with a for() loop. In that loop, mylabel.text is updated many times. However, the actual label does not update on the screen until the method is done, updati

相关标签:
3条回答
  • 2020-12-05 22:14

    From my earlier comment:

    Note that this (runMode:beforeDate:) can have all kinds of bizarre side-effects. When you call runMode:beforeDate:, all kinds of things could happen in the middle of your loop. Timers could fire; WebKit can do all kinds of madness; delayed selectors can fire. This is a very dangerous trick. Sometimes useful, occasionally necessary (especially on Mac), but not a general-purpose tool.

    The better solution is to schedule your updates on the main dispatch queue:

      for (NSInteger i = 0; i < 10; i++) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, i * NSEC_PER_SEC), 
                       dispatch_get_main_queue(), ^{
          [self.label setText:[NSString stringWithFormat:@"%d", i]];
        });
      }
    

    This schedules 10 updates 1 second apart. It can be adapted to all kinds of other requirements without creating a blocking method on the main run loop.

    0 讨论(0)
  • 2020-12-05 22:23

    You can make the UI update by telling the run loop to run like this:

    for (NSInteger i = 0; i < 10; i++) {
        [label setText:...];
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
    }
    
    0 讨论(0)
  • 2020-12-05 22:36

    try

    [yourLabel setNeedsDisplay];
    
    0 讨论(0)
提交回复
热议问题