我能否通过UIScrollView的图层来动画化contentOffset属性?

25
我想使用CGPathRef来放大和滚动UIScrollView。因此,我认为我必须对UIScrollView的层属性进行动画处理?但是,我应该动画处理哪个属性才能使其等同于对UIView进行动画处理并设置其contentOffset属性和zoomScale属性?
这些不是CALayer的属性。
你有什么想法如何解决这个问题吗?再次强调,只想将scrollview移动到特定的contentOffset和zoomScale,但不一定是从点A到点B线性移动,分别缩放A到B。
我想使用CAKeyFrameAnimation和CGPathRef,但我不知道要动画处理哪些属性。
3个回答

60
你需要对bounds属性进行动画处理。实际上,这就是contentOffset属性在幕后所使用的。
示例:
CGRect bounds = scrollView.bounds;

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"bounds"];
animation.duration = 1.0;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

animation.fromValue = [NSValue valueWithCGRect:bounds];

bounds.origin.x += 200;

animation.toValue = [NSValue valueWithCGRect:bounds];

[scrollView.layer addAnimation:animation forKey:@"bounds"];

scrollView.bounds = bounds;

如果你好奇,我曾经获取这些信息的方法如下:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];

[scrollView setContentOffset:CGPointMake(200, 0) animated:NO];

[UIView commitAnimations];

NSLog(@"%@",scrollView);

NSLog调用将输出:

<UIScrollView: 0x860ba20; frame = (-65.5 0; 451 367); clipsToBounds = YES; autoresize = W+RM+TM+H; animations = { bounds=<CABasicAnimation: 0xec1e7c0>; }; layer = <CALayer: 0x860bbc0>; contentOffset: {246, 0}>

animations代码片段将列出所有活动的动画,在此示例中为{ bounds=<CABasicAnimation: 0xec1e7c0>; }

希望这可以帮助到你。


我在使用其他动画技术(例如块动画)来正确地对我的scrollView进行动画处理时遇到了很多麻烦。但这个方法非常有效! - John Stephen
@pt2ph8,我喜欢像你这样的程序员,非常鼓舞人心。纯粹的令人敬畏! - Archy Will He 何魏奇
1
哇,关于边界和contentOffset之间的联系,你抓得真好。 - migs647

0

Swift 4.2

这个例子基于pt2ph8的obj-c答案。

https://dev59.com/cWw15IYBdhLWcg3wkMjz#8741283

var scrollView = UIScrollView()

func animateScrollView(duration: Double, to newBounds: CGRect) {
    let animation = CABasicAnimation(keyPath: "bounds")
    animation.duration = duration
    animation.fromValue = scrollView.bounds
    animation.toValue = newBounds

    animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)

    scrollView.layer.add(animation, forKey: nil)

    scrollView.bounds = newBounds
}

0
移动CALayer的方法是通过(最好)设置其.position属性,或者可能是anchorPoint(请参阅文档:http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Reference/CALayer_class/Introduction/Introduction.html)。
...但是如果您正在使用UIScrollView,则不建议您操作CALayer。您尝试将普通的CoreAnimations应用于ScrollView了吗?
(问题在于:UIScrollView是在CALayer之上实现的-因此即使您今天可以将其破解以正常工作,它很可能会在未来的iOS版本中出现问题。如果可能的话,您要避免使用CALayer来处理该特定类)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接