簡體   English   中英

當我的應用程序進入后台時,為什么我的無限UIView動畫會停止?

[英]Why does my indefinite UIView animation stop when my application goes to the background?

我使用以下代碼無限制地動畫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];

如果我的應用程序轉到后台,然后我返回它,那么所有這樣的動畫現在都停止了。 為什么會這樣?

通常,當應用程序執行到后台時,它的執行完全被暫停。 即使您的應用程序保持活動狀態(用於位置跟蹤,VoIP或其他原因),當您的應用程序移至后台狀態時,任何繪制到屏幕的內容都將停止

避免更新您的窗口和視圖。 在后台,您的應用程序的窗口和視圖不可見,因此您不應嘗試更新它們。 雖然在后台創建和操作窗口和視圖對象不會導致應用程序終止,但是應該推遲此工作,直到應用程序移動到前台。

實際上,如果您嘗試在后台繪制OpenGL ES上下文,您的應用程序將立即崩潰

不要從代碼中進行任何OpenGL ES調用。 在后台運行時,不得創建EAGLContext對象或發出任何類型的OpenGL ES繪圖命令。 使用這些調用會立即終止您的應用程序。

通常,建議暫停應用程序移動到后台的任何動畫,然后在應用程序位於前台后恢復這些動畫。 這可以在-applicationDidEnterBackground:-applicationWillEnterForeground:委托方法中處理,或者通過偵聽UIApplicationDidEnterBackgroundNotificationUIApplicationWillEnterForegroundNotification通知來處理。

正如@BradLarson在他的回答中建議的那樣,我已經添加了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];
}

當應用程序進入后台時,iO會停止執行代碼。 看一下這個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM