我使用以下代码无限期地动画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];
如果我的应用程序转到后台,然后我返回它,那么所有这样的动画现在都停止了。为什么会发生这种情况?
答案 0 :(得分:10)
通常,当应用程序执行到后台时,它的执行完全被暂停。即使您的应用程序仍处于活动状态(用于位置跟踪,VoIP或其他原因),当您的应用程序移至后台状态时,任何可以吸引到屏幕will be halted的内容:
避免更新您的窗口和视图。 在后台,你的 应用程序的窗口和视图是 不可见,所以你不应该尝试 更新它们。虽然创造和 操纵窗口和查看对象 在后台不会导致你的 申请被终止,这个 工作应推迟到你的工作 应用程序移到前台。
事实上,如果您尝试在后台绘制OpenGL ES上下文,那么您的应用程序will immediately crash:
不要进行任何OpenGL ES调用 你的代码。你不能创建一个 EAGLContext对象或发出任何OpenGL ES绘制任何类型的命令 在后台运行。使用这些 调用导致您的应用程序 立即终止。
通常,建议暂停将应用程序移动到后台的任何动画,然后在应用程序位于前台后恢复这些动画。这可以在-applicationDidEnterBackground:
和-applicationWillEnterForeground:
委托方法中处理,也可以通过收听UIApplicationDidEnterBackgroundNotification
和UIApplicationWillEnterForegroundNotification
通知来处理。
答案 1 :(得分:0)
正如@BradLarson在answer中建议的那样,我在视图控制器中添加了NSNotificationObserver
来处理UIApplicationDidEnterBackgroundNotification
和UIApplicationWillEnterForegroundNotification
。
- (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];
}
答案 2 :(得分:-2)
当应用程序进入后台时,iO会停止执行代码。 Check this out.