我正在尝试异步加载视图。问题是要加载的视图的帧取决于异步加载的数据。换句话说,有一些长计算决定了实际显示UIViews的位置。
我知道在尝试在线程中实际显示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容器中。
答案 0 :(得分:3)
尝试这样的事情:
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);
这会在主线程中添加您的按钮,但最初会使其不可见。完成后台工作后,您将使其可见并使用动画设置框架。