【问题标题】:Update UILabel in a "while loop"在“while 循环”中更新 UILabel
【发布时间】:2012-05-02 09:27:36
【问题描述】:

我正在尝试在“while 循环”中更新 UILabel,但它不会更改 UILabel 文本。我知道它像往常一样在主线程的当前运行循环周期结束时显示为iOS。但是如何解决这个问题(ftp.AsyncFinished函数是由外部chilkat ftp模块提供的):

数据每秒更新一次。我搜索了这个论坛和 Apple 的文档,但我找不到在主线程的“while 循环”中更新 UILabel 的正确方法。我可以用什么来代替while循环,它允许主线程更新UILabel

while (ftp.AsyncFinished != YES) {
    // here is the code getting data from the cilkat FTP module stored in PercentOfFile and MinutesRemaining
    NSString *content =[[NSString alloc] initWithFormat:@"%.0f%% done%.0fmin left",PercentOfFile,MinutesRemaining ];
    [LabelProgress setText:content];
}

【问题讨论】:

标签: objective-c ios while-loop uilabel


【解决方案1】:

为了让 UI 完全更新,主线程的运行循环必须完成。这意味着您的方法(如果在主线程上调用)必须在任何 UI 更新发生之前返回。然后合并所有更新并重绘 UI。

有关更多背景信息,请参阅What is the most robust way to force a UIView to redraw?

您的 while 循环被错误地设计为异步更新。您不应该在 while 循环的中间获取异步数据。您应该注册某种回调(通常将自己设置为delegate),然后等待系统呼叫您。

【讨论】:

    【解决方案2】:

    您需要在另一个线程中调用您的上传进度并注册回调。创建一个继承自具有此方法的 CkoFTP2Progress 的自定义类:

    - (void)PercentDone: (NSNumber *)pctDone abort:(BOOL *)abort;
    

    假设您有一个名为“ftp”的 CkoFTp2 对象和名为“UploadProgress”的自定义类,请注册回调:

    [self.ftp setEventCallbackObject:self.uploadProgress];
    

    【讨论】:

      【解决方案3】:

      您可以将 while 循环移动到后台线程并使用 performSelectorOnMainThread 从那里调用 setText。

      【讨论】:

      • ...或者只是在主线程中运行一个计时器来更新标签。
      • 由于连接到外部 FTP 模块,无法将 while 循环移动到后台处理。我怎样才能用计时器做到这一点?
      【解决方案4】:
      // update your UILabel here
      // ...
      
      // Delay execution of long-running task so that update of UILabel can be performed
      dispatch_after( dispatch_time( DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC ), dispatch_get_main_queue(), ^{
           // long-running task 
           // ..
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-28
        • 1970-01-01
        • 2018-08-17
        • 1970-01-01
        • 2019-12-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多