我有一个启用分页的scrollView和N个页面,这些页面是UIViews作为scrollView的 subview 。
我正在尝试执行以下操作:
用户滚动到页码n。
此时,先前已添加到第n页的7个CALayer
(即,到页面[[scrollView subviews] objectAtIndex:n-1] .layer subLayers]的淡入淡出,一个接一个。
但是我无法弄清楚如何使CALayers渐入渐进。到目前为止,我已经从 Controller 的委托(delegate)方法中尝试了以下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 = @(0);
a.toValue = @(1);
a.fillMode = kCAFillModeForwards;
a.beginTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil] + timeOffset;
a.duration = 0.8;
a.removedOnCompletion = NO;
[layer addAnimation:a forKey:nil];
timeOffset += a.duration;
}
[CATransaction commit];
在上述情况下,引用框架只是调用发生的当前时间。
关于ios - 我如何才能依次链接不同图层的核心动画?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9122756/