2010-05-17 29 views
16

我想以淡入通過手動淡入新添加的子視圖?

[self.view addSubview:someSecondaryViewController.view];

被添加到堆棧時,我如何動畫此調用,這樣的觀點在逐漸消失(進出)?

回答

29

在動畫之前將alpha設置爲零,然後將alpha設置爲1。

[fadingView setAlpha:0.0]; 
[containerView addSubview:fadingView]; 
[UIView beginAnimations:nil context:nil]; 
[fadingView setAlpha:1.0]; 
[UIView commitAnimations]; 

在拆除觀點,只是動畫阿爾法回零。

順便說一下,視圖層次結構比堆棧更像樹。

編輯:

如果沒有其他清理淡出視圖時動畫結束後,再使用:

[UIView setAnimationDelegate:fadingView]; 
[UIView setAnimationDidStopSelector:@selector(removeFromSuperview)]; 

如果你已經設置didStopSelector然後調用removeFromSuperview那裏。

+0

當我的淡入在0.0結束時會發生什麼?這似乎是刪除我的子視圖。我希望發生這種情況,但是我應該擔心內存管理嗎?如果我明確添加代碼以刪除子視圖,則不會顯示動畫。 – Moshe 2010-05-17 00:59:34

+1

使用'+ setAnimationDidStopSelector'方法從超級視圖中移除'fadingView'。 – 2010-05-17 03:54:09

21

你也可以使用塊從超級視圖刪除一個視圖,它已經完成淡出後的​​動畫:

[UIView animateWithDuration:0.2 
       animations:^{viewOut.alpha = 0.0;} 
       completion:^(BOOL finished){[viewOut removeFromSuperview];}]; 
0

而且在斯威夫特...

In

someSecondaryViewController.view.alpha = 0.0 
self.view.addSubview(someSecondaryViewController.view) 
UIView.animateWithDuration(0.2, animations: { self.someSecondaryViewController.view.alpha = 1.0 }) 

Out

UIView.animateWithDuration(0.2, animations: { self.someSecondaryViewController.view.alpha = 0.0 }) { (done:Bool) in 
     self.someSecondaryViewController.view.removeFromSuperview() 
}