我想在按下按钮时加载一些数据,并在加载时显示“加载视图”作为当前视图的子视图。
所以我想在子视图出现后才开始加载。如果不是我的UI在没有通知的情况下卡住(并且子视图仅在加载完成后显示)。
有没有办法像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,这不是线程安全的。)
谢谢!
答案 0 :(得分:2)
我找到了解决方案:
使用动画添加子视图我可以使用- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
来调用子视图委托的subviewDidAppear
之类的内容。
在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];
}
}
这让我得到了我想要的结果。
再次感谢您的帮助!
答案 1 :(得分:1)
您应该能够在调用[parentView addSubview:loadingView]
之后直接开始加载,或者在加载视图中(假设它是子类)覆盖didMoveToSuperview,如下所示:
- (void)didMoveToSuperview {
// [self superview] has changed, start loading now...
}