2011-03-29 74 views
3

我想加载一些数据时,按下按钮,并显示一个“加载视图”作为我当前视图加载时的子视图。viewDidAppear子视图

所以我想在子视图出现之后才开始加载。如果不是,我的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我的工作,这不是线程安全的)。

谢谢!

回答

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

您应该能够简单地启动加载调用[parentView addSubview:loadingView]后或在您的加载视图(假设它是子类)重载didMoveToSuperview像这样:

- (void)didMoveToSuperview { 
    // [self superview] has changed, start loading now... 
} 
+0

不起作用。 'didMoveToSuperview'并不意味着子视图确实出现,而只是它已经被添加到超级视图。 如果我开始在'didMoveToSuperview'中加载,只有在加载数据后,子视图才会显示。 – Jochen 2011-03-29 12:11:12

+0

当你说“加载”时,你在做什么?您是否正在等待网络操作或执行某种计算? – 2011-03-29 12:22:08

+0

我从CoreData数据库加载数据。 – Jochen 2011-03-29 12:27:31