2011-03-29 75 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