我想在按下按钮时加载一些数据,并在加载时显示“加载 View ”作为当前 View 的 subview 。
所以我只想在 subview 确实出现后才开始加载。否则我的 UI 会在没有通知的情况下卡住(并且 subview 仅在加载完成后显示)。
有没有办法为 subview 使用类似viewDidAppear
的东西?
在 addSubview 之后立即执行工作:
像这样不起作用:
- (void)doSomeWorkAndShowLoadingView
{
UIView *loadingView = [[[UIView alloc] initWithFrame:self.view.frame] autorelease];
loadingView.backgroundColor = [UIColor redColor];
[self.view addSubview:loadingView];
[self doSomeWork];
[loadingView removeFromSuperview];
}
- (void)doSomeWork
{
sleep(5);
}
(我不想在新线程上加载,因为我正在处理的是 CoreData,它不是线程安全的)。
谢谢!
最佳答案
我找到了一个解决方案:
添加带有动画的 subview 我可以使用 - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
来调用类似 subviewDidAppear
的东西 subview 的代表。
在 UIView 的子类中:
#define KEY_SHOW_VIEW @"_ShowLoadingView_"
#define KEY_HIDE_VIEW @"_HideLoadingView_"
- (void)addToSuperview:(UIView *)theSuperview
{
[theSuperview addSubview:self];
CATransition *animation = [CATransition animation];
[animation setDuration:0.2];
[animation setType:kCATransitionFade];
[animation setDelegate:self];
[animation setRemovedOnCompletion:NO];
[animation setValue:KEY_SHOW_VIEW forKey:@"animation_key"];
[[theSuperview layer] addAnimation:animation forKey:nil];
}
- (void)removeFromSuperview
{
CATransition *animation = [CATransition animation];
[animation setDuration:0.2];
[animation setType:kCATransitionFade];
[animation setDelegate:self];
[animation setRemovedOnCompletion:NO];
[animation setValue:KEY_HIDE_VIEW forKey:@"animation_key"];
[[self.superview layer] addAnimation:animation forKey:nil];
[super removeFromSuperview];
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
NSString* key = [anim valueForKey:@"animation_key"];
if ([key isEqualToString:KEY_SHOW_VIEW]) {
if (self.delegate) {
if ([self.delegate respondsToSelector:@selector(loadingViewDidAppear:)]) {
[self.delegate loadingViewDidAppear:self];
}
}
} else if ([key isEqualToString:KEY_HIDE_VIEW]){
[self removeFromSuperview];
}
}
这让我得到了我想要的结果。
再次感谢您的帮助!
关于iphone - viewDidAppear 用于 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5470552/