我有一个scrollView启用分页和N个页面,它们是UIViews作为scrollView的子视图.
我正在尝试执行以下操作:
用户滚动到页码n.
此时,7个CALayers先前添加到页码n
(即,[[scrollView subviews] objectAtIndex:n-1] .layer subLayers])逐渐淡入淡出.
但是我无法弄清楚如何使CALayers依次淡入淡出.至此,我从控制器的委托方法中尝试了以下3种方法:
(假设我有一个数组到图层,并且它们的不透明度在创建时被设置为0)
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { int pageNumber = floor(self.scrollView.contentOffset.x / self.scrollView.frame.size.width); if(pageNumber == (n-1)) { int timeOffset = 0; [CATransaction begin]; for(CALayer *layer in layerArray) { CABasicAnimation *a = [CABasicAnimation animationWithKeyPath:@"opacity"]; a.duration = 6; a.beginTime = timeOffset++; a.fromValue = [NSNumber numberWithFloat:0.]; a.toValue = [NSNumber numberWithFloat:1.]; [layer addAnimation:a forKey:nil]; } [CATransaction commit]; } } - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { int pageNumber = floor(self.scrollView.contentOffset.x / self.scrollView.frame.size.width); if(pageNumber == (n-1)) { int timeOffset = 0; [CATransaction begin]; for(CALayer *layer in layerArray) { CABasicAnimation *a = [CABasicAnimation animation]; a.duration = 6; a.beginTime = timeOffset++; [layer addAnimation:a forKey:@"opacity"]; [layer setOpacity:1]; } [CATransaction commit]; } } - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { int pageNumber = floor(self.scrollView.contentOffset.x / self.scrollView.frame.size.width); if(pageNumber == (n-1)) { int timeOffset = 0; for(CALayer *layer in layerArray) { [CATransaction begin]; CABasicAnimation *a = [CABasicAnimation animation]; a.duration = 6; a.beginTime = timeOffset++; [layer addAnimation:a forKey:@"opacity"]; [layer setOpacity:1]; } for(CALayer *layer in layerArray) [CATransaction commit]; } }
但似乎没有工作.当用户滚动到正确的页面时,所有图层都可以立即显示,没有太多的淡入淡定,绝对不会以任何顺序排列.
有任何想法吗?
解决方法
实际上,事实证明,关键是获得当前时间的参考框架,并添加任何时间偏移到当前时间.这也适用于非分组动画.
例如,沿着这段代码的东西会导致n个层(假定存储在某个数组中)依次逐渐淡入淡出,每次取0.8秒.
CGFloat timeOffset = 0; [CATransaction begin]; for(CALayer *layer in layers) { CABasicAnimation *a = [CABasicAnimation animationWithKeyPath:@"opacity"]; a.fromValue = [NSNumber numberWithFloat:0.]; a.toValue = [NSNumber numberWithFloat:1.]; a.fillMode = kCAFillModeForwards; a.beginTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil] + timeOffset; a.duration = .8; a.removedOnCompletion = NO; [layer addAnimation:a forKey:nil]; timeOffset += .8; } [CATransaction commit];
在上述情况下,参考框架仅仅是调用发生的当前时间.