ios - 异步加载 UIView

标签 ios multithreading uiview asynchronous nsoperationqueue

我正在尝试异步加载 View 。问题在于要加载的 View 的框架取决于异步加载的数据。换句话说,有一些长时间的计算来决定 UIView 的实际显示位置。

我知道尝试在线程中实际显示 UIView 时会出现问题,并且您应该始终将它们加载回主线程中,所以这是我一直在尝试的代码:

asyncQueue = [[NSOperationQueue alloc] init];
[asyncQueue addOperationWithBlock:^{
    // Do work to load the UIViews and figure out where they should be
    UIButton *test = [[UIButton alloc] initWithFrame:[self doWorkToGetFrame]];

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [self addSubview:test];
        }
    }];
}];

这一切都驻留在 UIView 容器中。

最佳答案

尝试这样的事情:

UIButton *test = [[UIButton alloc] initWithFrame:CGRectZero];
test.hidden = YES;
test.alpha = 0.0f;
[self addSubview:test];

dispatch_queue_t downloadQueue = dispatch_queue_create("myDownloadQueue",NULL);
dispatch_async(downloadQueue, ^
{
  // do work to load UIViews and calculate frame
  CGRect frameButton = ...;

  dispatch_async(dispatch_get_main_queue(), ^
  {
    test.hidden = NO; 
    [UIView animateWithDuration:0.4f animations:^
    {
     test.frame = frameButton;
     test.alpha = 1.0f;
    } 
    completion:^(BOOL finished){}];


  });
});

dispatch_release(downloadQueue);

这会将您的按钮添加到主线程中,但最初会使其不可见。背景工作完成后,您将使其可见并使用动画设置框架。

关于ios - 异步加载 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12373850/

相关文章:

c# - 线程同步 XNA 网络

ios - IB 中 3.5 外形尺寸的不同 View

ios - Uibutton 的 titleLabel.textColor

ios - 如何在不弄乱内容的情况下标记 dequeueReusableCell?

ios - MVVM 在 iOS 中的使用

c++ - 线程安全并发调用C++中的外部命令

multithreading - POSIX 线程与 Win32 线程

ios - 在 ViewController 中创建选项卡 View 的最佳方法是什么

iphone - 使用 UITabBarController 添加持久化 UIView

iphone - 无法让 UIView sizeToFit 做任何有意义的事情