2011-01-12 43 views
2

我使用下面的代碼無限期動畫一個UIView:爲什麼我的應用程序轉到後臺時,我的無限UIView動畫會停止?

#define DEFAULT_ANIM_SPPED 0.6 
#define INFINATE_VALUE 1e100f 

[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationRepeatAutoreverses:YES]; 
[UIView setAnimationRepeatCount:INFINATE_VALUE]; 
[UIView setAnimationDuration:DEFAULT_ANIM_SPPED]; 
CGRect tempFrame=myView.frame; 
tempFrame.origin.y -= 30; 
myView.frame=tempFrame; 
[UIView commitAnimations]; 

如果我的應用程序轉到後臺,然後我回到它,這樣所有的動畫,現在停止。爲什麼會發生這種情況?

回答

10

通常,當它轉到後臺應用程序的執行完全暫停。即使您的應用程序仍然處於活動狀態(位置跟蹤,網絡電話,或其他原因),任何吸引到屏幕will be halted當你的應用程序移動到後臺狀態:

避免更新您的窗口和視圖。 而在後臺,你 應用程序的窗口和視圖 不可見的,所以你不應該試圖 更新它們。儘管在後臺創建並查看對象 並不會導致您的 應用程序被終止,但應該推遲這個 工作,直到您的 應用程序移至前臺。

事實上,如果你嘗試繪製在後臺的OpenGL ES的背景下,您的應用程序will immediately crash

不要做任何的OpenGL ES從 代碼調用。你不能創建一個 EAGLContext對象或發出任何的OpenGL ES 繪製任何種類的命令,而 在後臺運行。使用這些呼叫將導致您的應用程序立即終止 。

通常,建議暫停應用程序移動到背景的任何動畫,然後在應用程序處於前景時恢復這些動畫。這可以在-applicationDidEnterBackground:-applicationWillEnterForeground:委託方法,或通過聆聽UIApplicationDidEnterBackgroundNotificationUIApplicationWillEnterForegroundNotification通知辦理。

+0

感謝您的有用的信息。 – 2011-01-13 04:41:16

-2

當應用程序進入後臺時,iOs會停止執行代碼。 Check this out.

0

由於@BradLarson在他answer建議,我已經加入NSNotificationObserver處理UIApplicationDidEnterBackgroundNotificationUIApplicationWillEnterForegroundNotification在我的視圖控制器。

- (void) addNotificationObserver { 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil]; 
} 

- (void) removeNotificationObserver { 
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil]; 
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil]; 
} 

- (void) applicationDidEnterBackground:(NSNotification *)notification { 
    // went to background 
} 

- (void) applicationWillEnterForeground:(NSNotification *)notification { 
    // comes to foreground 
} 

- (void) viewDidLoad { 
    [super viewDidLoad]; 
    [self addNotificationObserver]; 
} 

- (void) dealloc { 
    [self removeNotificationObserver]; 
} 
相關問題