我花了一个星期的时间想弄清楚如何做到这一点。
我想做的是显示一个 subview ,然后对后端进行 http 调用,然后删除 subview 。
...
//Display view
[superView addSubview:blurredOverlay];
[superView bringSubviewToFront:blurredOverlay];
//After blurredOverlay is displayed, Try to login the user
dispatch_group_t d_group = dispatch_group_create();
dispatch_queue_t bg_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_async(d_group, bg_queue, ^{
//Try to login user
success = [self loginUser];
NSLog(@"Success=%i", success);
[NSThread sleepForTimeInterval:10.0]; //here to force thread to not return immediatly
});
dispatch_group_wait(d_group, DISPATCH_TIME_FOREVER);
//Remove the view after the thread is done processing
[blurredOverlay removeFromSuperview];
这是行不通的。如果我有
[blurredOverlay removeFromSuperview];
未注释,blurredOverlay 永远不会显示。如果我将其注释掉,则会显示 blurredOvleray,但我显然无法将其删除。
我需要的是先显示 blurredOverlay,然后尝试登录用户(同时显示 blurredOverlay),并在 loginUser 返回后,移除模糊显示。
最佳答案
您正在将此 block 分派(dispatch)到异步队列。您的主线程不会停止等待该 block 完成。
但你已经知道了。这就是为什么您使用调度组来阻塞主线程,直到后台任务完成。
该方法的问题在于,UI 仅在运行循环完成当前迭代后刷新。直到你的方法离开时,这种情况才会发生。
这是您的代码运行时发生的情况:
- UI由系统更新
- 您的方法已输入
- 添加 View
- 调度 block
- 等待 block 完成
- 删除 View
- 留下你的方法
- UI由系统更新
你看到问题了吗?在添加 View 和删除 View 之间,UI 不会更新。
这是你应该做的。您添加 View 。将 block 与您的任务一起调度,以便它在后台运行。在该后台 block 结束时,您调度另一个 block ,该 block 将在后台任务完成时运行。该 block 在主线程上运行并删除您的 View 。
[superView addSubview:blurredOverlay];
dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(backgroundQueue, ^{
// run your web request here
[NSThread sleepForTimeInterval:10.0];
// task is done
dispatch_async(dispatch_get_main_queue(), ^{
// UI updates have to run on the main thread, so dispatch the removal
[blurredOverlay removeFromSuperview];
});
});
关于ios - 等待 subview 显示,然后处理,然后移除 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27325785/