使用CoreAnimation实现UIScrollView的滚动动画

17

非常抱歉我的问题比较冗长,实际问题在底部用粗体标出,现在简要解释一下。

我在项目中使用CoreAnimation来实现对象的移动动画,就像这样。

CABasicAnimation *moveAnimation;        
moveAnimation=[CABasicAnimation animationWithKeyPath:@"position"];      
moveAnimation.duration = 2.0;       
moveAnimation.repeatCount=1;        
moveAnimation.autoreverses=NO;  
moveAnimation.delegate = self;
moveAnimation.fromValue = [NSValue valueWithCGPoint:[crawler.layer position]];
moveAnimation.fillMode = kCAFillModeForwards;
moveAnimation.removedOnCompletion = NO;
CGPoint p;
moveAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(100, 100)];
[crawler.layer addAnimation:moveAnimation forKey:@"moveAnimation"];

现在我需要对某个UIScrollView进行滚动动画。我不能使用setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated方法,因为它无法自定义动画持续时间。

我可以像这样实现:

CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
[UIView setAnimationDuration:2];
[UIView setAnimationDelegate:self];
scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x + 200, scrollView.contentOffset.y);
[UIView commitAnimations];

但这并不是CoreAnimation,而且在一个应用程序中使用两种不同的动画技术并不是一个好的实践,我认为。

有没有一种方法可以使用CoreAnimation来动画滚动UIScrollView内容到自定义点,并指定自定义动画持续时间? P.S. 抱歉我的英语不好。

4个回答

28

您可以使用:

[UIView animateWithDuration:duration animations:^ {
    [scrollView setContentOffset:destination animated:NO];
}];

你可以通过以下方式设置动画的持续时间。


可以,但这是块动画,不是核心动画,对吧?我需要一种使用核心动画的方法,因为已经在项目中使用它,不想使用两种不同的技术。 - Padavan
令人惊喜的简单回答是关于持续时间问题的一部分。 - PKCLsoft
3
"block animation" 只是包装了核心动画技术,而不是一种不同的技术。你可以自由地混合它们使用。 - skozin

7
[UIScrollViewNameHere setContentOffset:CGPointMake(x value of where you want to move to, y value of where you want to move to) animated:YES];

例如:
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(4, 2, 2341, 412)];
[scroll setContentOffset:CGPointMake(320, 0) animated:YES];

我无法使用setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated方法,因为它无法自定义动画持续时间。我在问题中写了它,请仔细阅读。 - Padavan

5
您应该了解可动画属性,《iOS 5编程》可以提供一些可动画属性,但您不必局限于此。您可以动画任何您想要的东西。
在所有情况下,您不应该使用kCAFillModeForwards,因为它将要求设备无限制地重新绘制上次用于动画的最后一个呈现层,而不是使用缓存表示层。
因此,您可以通过定义自己的特定图层来实现这样的事情,其中contentOffset属性被定义为可动画。为了使其工作,您应该首先验证滚动视图使用了哪种顶层类,以便通过子类化并设置所需属性(contentOffset)可动画,并将此图层设置为滚动视图的顶层,从而可能实现您正在尝试做的事情。
这是理论!
但这是我会尝试的方法。 查找此方法及其行为和意图。
+ (BOOL)needsDisplayForKey:(NSString *)key

您可以阅读的另一件事是这个起始示例。但这也意味着您需要自己重新绘制您的uiscrollview!


非常感谢。这正是我现在需要的。 - Padavan

4

我认为你无法使用CoreAnimation来动画化点。

但是你可以尝试使用setContentOffset:animated:这个方法,这可能是你正在寻找的方法?

你只能转换以下UIView的属性:

  • frame
  • bounds
  • center
  • transform
  • alpha
  • backgroundColor
  • contentStretch

有关动画的更多信息,请查看Apple文档


谢谢您的回答,但是对于我的情况,setContentOffset:animated: 方法不适用,因为我需要设置动画持续时间。并且您提供的链接不是关于核心动画的。这是相关文档:https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreAnimation_guide/Introduction/Introduction.html - Padavan

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