今天需求說要給在進入某個頁面給某個按鈕加上放大效果,心想這還不簡單,於是三下五除二的把動畫加上提交測試了.
下面是動畫的代碼
NSTimeInterval time = CACurrentMediaTime(); time = time + 0.5; CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"]; //設置value CATransform3D scale1 = CATransform3DMakeScale(1.1, 1.1, 1); CATransform3D scale2 = CATransform3DMakeScale(1.0, 1.0, 1); animation.values = @[[NSValue valueWithCATransform3D:scale2],[NSValue valueWithCATransform3D:scale1],[NSValue valueWithCATransform3D:scale2]]; //重復次數 默認為1 animation.repeatCount = 1; //設置是否原路返回默認為NO animation.autoreverses = NO; animation.beginTime = time; animation.duration = 0.5; animation.keyTimes = @[@0.0,@0.7,@1]; animation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; //給這個view加上動畫效果 [view.layer addAnimation:animation forKey:@"transform.scale"];
然而后面卻出現了一個詭異的bug.當動畫正在進行的時候滾動scrollView,則會崩潰,並且報下面的錯誤.
[NSConcreteValue doubleValue]: unrecognized selector sent to instance
上stackoverflow上發現解釋如下,
The transform.scale should be a double type, if you assign fromValue or toValue of CABasicAnimation a NSValue type, it cann't convert to double value, and so App crashed.
翻譯一下就是transform.scale應該用double類型的數值來賦值,如果用NSValue封裝好的值來給fromValue和toValue賦值的話,則會解析不到對應的值,表現為app崩潰.
於是修改代碼如下,完美運行,不會崩潰了.
NSTimeInterval time = CACurrentMediaTime(); time = time + 0.5; //設置value CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"]; //設置value animation.values = @[@1,@1.1,@1]; //重復次數 默認為1 animation.repeatCount = 1; //設置是否原路返回默認為NO animation.autoreverses = NO; animation.beginTime = time; animation.duration = 0.5; animation.keyTimes = @[@0.0,@0.7,@1]; animation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; //給這個view加上動畫效果 [view.layer addAnimation:animation forKey:@"transform.scale"];