UIView下使用Animation控制动画

时间:2023-03-08 16:11:34

转载自:http://blog.csdn.net/xunyn/article/details/8128031

动画效果是IOS界面重要的特色之一,其中CAAnimation是所有动画对象的抽象父类,作为新人,使用较多的是UIView下的动画方法(类方法)。使用UIView下的动画,有下面几个方法。

方法一:设置beginAnimations

其中memberView为需要添加的子视图的视图,mivc.view为子视图,在使用的时候,需要将这两个地方替换

  1. [UIView beginAnimations:@"view flip" context:nil];
  2. [UIView setAnimationDuration:1];
  3. [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:memberView cache:YES];
  4. [memberView addSubview:mivc.view];
  5. [UIView commitAnimations];

需要注意的是,一定要使用[UIView commitAnimations];动画才会生效

通过[UIView setAnimationDuration:1]; 设置持续时间。

在IOS4.0后,我们有了新的方法,+ (void)transitionWithView:(UIView *)view duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion,依然是UIView的类方法,但使用到了Block对象,Block对象是一组指令,可以传递(像变量一样),可以把它想像成C语言的函数指针。

方法二:

其中在当前视图下,删除[blueViewController view],添加[yellowViewController view],在使用时,这两个地方要替换

  1. [UIView transitionWithView:self.view
  2. duration:0.2
  3. options:UIViewAnimationOptionTransitionFlipFromLeft
  4. animations:^{ [[blueViewController view] removeFromSuperview]; [[self view] insertSubview:yellowViewController.view atIndex:0]; }
  5. completion:NULL];

其中animations:后的block为对特定视图发生的改变,其不能为是NULL,completion:后block为动画执行完后,需要执行的代码块,可以为NULL。

根据手册,在整个动画过程中,用户交互对于此视图是暂时无效的(而IOS5.0前,动画过程中,用户交互对于整个应用是无效的),如果想要用户可以和视图交互,可以改变 UIViewAnimationOptionAllowUserInteraction 的值。

另外,还可以使用例如这种:

// 在中间消失的动画

[UIView animateWithDuration:0.3f animations:^{

self.transform = CGAffineTransformMakeScale(0.1f, 0.1f);

self.alpha = 0.f;

} completion:^(BOOL finished) {

}];

//上下扫动的动画

[UIView animateWithDuration:2.8 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{

_lineImageView.frame = CGRectMake(30, 260, 220, 2);

} completion:^(BOOL finished) {

_lineImageView.frame = CGRectMake(30, 10, 220, 2);

}];