CADisplayLink && 双击 home 键的时候, 动画不会暂停

  1. NSTimer CADisplayLink
    • 通过 NSTimer 实现的动画可能造成卡顿、不连贯的情况(NSTimer 不准确)
    • CADisplayLink 表示"显示连接", 与显示器的刷新频率相关。
    • 显示器每秒钟刷新60次(60HZ)(电视新闻上拍的电脑显示器就不清楚,原因刷新频率不一样)
    • 通过 CADisplayLink 来解决
/** 参考代码:
 // 核心代码
 CADisplayLink *timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(moveSecond)];
 [timer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

 - (void)viewDidLoad {
 [super viewDidLoad];
 // 1. 创建表盘
 UIView *clockView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
 clockView.backgroundColor = [UIColor blueColor];
 clockView.center = CGPointMake(self.view.bounds.size.width * 0.5, self.view.bounds.size.height * 0.5);
 [self.view addSubview:clockView];
 self.clockView = clockView;
 
 
 // 2. 创建秒针
 UIView *secondView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 50)];
 secondView.backgroundColor = [UIColor redColor];
 secondView.layer.anchorPoint = CGPointMake(0.5, 1);
 secondView.center = clockView.center;
 [self.view addSubview:secondView];
 self.secondView = secondView;
 
 
 [self moveSecond];
 
 // 3. 启动一个计时器, 每隔一秒钟计算一下当前秒针的位置, 然后做一次哦旋转操作
 // [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(moveSecond) userInfo:nil repeats:YES];
 
 CADisplayLink *timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(moveSecond)];
 [timer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
 }
 
 - (void)moveSecond
 {
 // 1. 计算当前的秒数
 NSDate *nowDate = [NSDate date];
 NSCalendar *calendar = [NSCalendar currentCalendar];
 NSInteger seconds = [calendar component:NSCalendarUnitSecond fromDate:nowDate];
 // 2. 计算每一秒的弧度
 CGFloat rotation = M_PI * 2 / 60;
 // 3. 用每一秒的弧度 * 秒数 , 计算出本次要旋转的弧度
 rotation = seconds * rotation;
 // 4. 旋转秒针
 self.secondView.transform = CGAffineTransformMakeRotation(rotation);
 }
 
 // 每次触摸一次屏幕秒针转一次
 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 {
 CGFloat rotation = M_PI * 2 / 60;
 self.secondView.transform = CGAffineTransformRotate(self.secondView.transform, rotation);
 }
 @end
 */
  1. 当双击 home 键的时候, 动画不会暂停
  • 注意: 如果当动画正在执行的时候, 将程序退出到后台, 那么当程序再次进入前台的时候就不执行了。
  • 原因: 因为再次进入前台后动画已经被删除了。
  • 解决1: anim.removedOnCompletion = NO;
  • 问题: 当双击 home 键的时候, 动画不会暂停。
  • 解决:
    /** 参考:
// 暂停
- (void)applicationWillResignActive:(UIApplication *)application {
ViewController *vc =  (ViewController *)self.window.rootViewController;
[vc pause];
}

// 恢复
- (void)applicationDidBecomeActive:(UIApplication *)application {
ViewController *vc =  (ViewController *)self.window.rootViewController;
[vc resume];
}
*/

你可能感兴趣的:(CADisplayLink && 双击 home 键的时候, 动画不会暂停)