應用程式最常見的狀態轉換之一,就是從「活動」過渡到「不活動」,再返回「活動」。本文透過一個實作範例,示範如何監聽並處理這些狀態變化,讓文字標籤的動畫能隨應用狀態暫停或恢復。
#import "ZYViewController.h"
@interface ZYViewController ()
@end
@implementation ZYViewController
@synthesize label;
@synthesize animate;
- (void)viewDidLoad
{
[super viewDidLoad];
// 註冊通知:即將進入不活動狀態
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:[UIApplication sharedApplication]];
// 註冊通知:恢復為活動狀態
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidBecomeActive:)
name:UIApplicationDidBecomeActiveNotification
object:[UIApplication sharedApplication]];
CGRect bounds = self.view.bounds;
CGRect labelFrame = CGRectMake(bounds.origin.x,
CGRectGetMidY(bounds)-50, bounds.size.width, 100);
self.label = [[UILabel alloc] initWithFrame:labelFrame];
label.font = [UIFont fontWithName:@"Helvetica" size:70];
label.text = @"Archy!";
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor clearColor];
[self.view addSubview:label];
}
- (void)dealloc {
[label release];
[super dealloc];
}
// 標籤向下旋轉
-(void)rotatelabelDown{
// 隱式動畫:Core Animation 會把屬性從目前值平滑過渡到指定值
[UIView animateWithDuration:0.5
animations:^{
// 為 transform 設定旋轉角度(以弧度為單位)
label.transform = CGAffineTransformMakeRotation(M_PI);
}
completion:^(BOOL finished){
// 完成後呼叫另一個方法,讓動畫持續循環
[self rotateLabelUp];
}];
}
// 標籤向上旋轉
-(void)rotateLabelUp{
[UIView animateWithDuration:0.5
animations:^{
label.transform = CGAffineTransformMakeRotation(0);
}
completion:^(BOOL finished){
// 加入判斷條件,只有處於活動狀態才持續動畫
if(animate)
[self rotatelabelDown];
}];
}
- (void)applicationWillResignActive:(UIApplication *)application
{
NSLog(@"%@", NSStringFromSelector(_cmd));
animate = NO;
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
NSLog(@"%@", NSStringFromSelector(_cmd));
animate = YES;
[self rotatelabelDown];
}
@end
啟動時主控台:
2013-06-08 13:20:24.265 State Lab[414:c07] application:didFinishLaunchingWithOptions: 2013-06-08 13:20:24.287 State Lab[414:c07] applicationDidBecomeActive:
按下 Home 鍵後:
2013-06-08 13:21:57.394 State Lab[414:c07] applicationWillResignActive: 2013-06-08 13:21:57.396 State Lab[414:c07] applicationDidEnterBackground:
再次開啟 App:
2013-06-08 13:22:44.051 State Lab[414:c07] applicationWillEnterForeground: 2013-06-08 13:22:44.052 State Lab[414:c07] applicationDidBecomeActive:
透過監聽這些通知,我們得以在應用離開與回到前景時,精準地暫停與恢復動畫,避免在背景中做無謂的運算。