3

我想在线程中加载一些视图以避免 UI 冻结等待加载结束。

我不习惯穿线,所以我做了一个快速测试。我的代码只是尝试在线程中创建视图并将此视图添加到主线程的当前视图控制器视图中。

我的 UIView 正在工作,但对于我的 UILabel,我必须等待 20-60 秒才能将其显示在屏幕上。

我使用 UIButton 进行了测试,在这种情况下,按钮会立即显示,但按钮内的标签显示的延迟与我的 UILabel 相同。

让它按我想要的方式工作的唯一方法是添加一个 [lbl setNeedsDisplay]; 在主线程中强制 UILabel 立即显示。为什么?没有这条线可以完成这项工作吗?

    dispatch_queue_t queue = dispatch_queue_create("myqueue", NULL);
dispatch_async(queue, ^{

    // NEW THREAD
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 48)];
    lbl.text = @"FOO";

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    view.backgroundColor = [UIColor redColor];

    // MAIN THREAD
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.view addSubview:lbl];
        [lbl setNeedsDisplay]; // Needeed to see the UILabel. WHY???

        [self.view addSubview:view];
    });
});
dispatch_release(queue);
4

1 回答 1

5

您还应该在主队列上设置标签的文本:

dispatch_async( dispatch_get_main_queue(), ^{
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 48)]
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    lbl.text = @"FOO";
    [self.view addSubview:lbl];
    [self.view addSubview:view];
});

最好将所有UI 内容保留在主队列中。

更新

它似乎initWithFrame:不是线程安全的(在SO 答案中找到,另请参阅文档中的线程注意事项)。UIView

于 2013-03-05T16:45:55.173 回答