UIView 提供了丰富的动画功能,这些功能使用简单而且进行了很好的优化。最为常见的动画可以用
+animateWithDuration:animations:和相关方法处理。你可以使用UIview为
frame、bounds、center、transform、alpha、BackgroundColor以及contentStretch添加动画效果。大多时候,我们是为frame、center、transform、alpha使用动画效果。
2、是在小球还处在动画时候忽略触摸事件。
-(void)viewDidLoad
{
[super viewDidLoad];
self.circleView = [[CircleView alloc] initWithFrame:CGRectMake(0,0,20,20)];
self.circleView.center = CGPointMake(100,20);
[[self view] addSubview:self.circleView];
UITapGestureRecognizer *g;
g = [[UITapGestureRecognizer alloc]initWithTarget:self action:@Selector(dropAnimate)];
[[self view] addGestureRecognizer:g];
}
...
-(void)dropAnimate
{
[UIView animateWithDuration:3 animations:^{self.circleView.center = CGPointMake(100,300);}];
}
以上的是一种基于视图的最简单动画,设计大部分的常见问题,尤其是通过动画变化大小、位置以及不透明性(alpha)。它也常用与做出缩放、旋转或平移的变形(transform)动画效果。较为不太常见的用法是对backGroundColor喝contentStretch 添加动画效果。改变背景颜色的动画HUD(Head Up Display,平视显示器)式界面中尤其有用,可以在近乎透明与近乎不透明的背景间变换。这比单纯改变alpha的动画效果更好。
连续动画(chaining animation)也很简单,如以下代码所示
-(void)dropAnimate
{
[UIView animateWithDuration:3 animations:^{self.circleView.center = CGPointMake(100,300);}
completion:(^BOOL finished){
[UIView animateWithDuration:1 animations:^{self.circleView.center = CGPointMake(250,300);}];
}];
}
但是现在小球会落下后一到右边。不过这段代码有个小问题。如果你在动画进行中触摸屏幕,小球就会先跳向左下方然后以动画效果移到右边。你可能并不希望出现这种情况。问题在于每次触摸屏幕,代码都会执行,如果动画还在进行中,这就会取消动画,而且completion代码块会按照finished == NO 的条件运行。下面将会解决这个问题。
要解决上面的问题有两种解决办法。
1、更改用户界面,使触摸小球时才会引发动画:
[self.circleView addGestureRecognizer:g];
2、是在小球还处在动画时候忽略触摸事件。
-(void)dropAnimate
{
[UIView animateWithDuration:3 animations:^{
recognnizer.enable = NO;
self.circleView.center = CGPointMake(100,300);}
completion:(^BOOL finished){
[UIView animateWithDuration:1 animations:^{self.circleView.center = CGPointMake(250,300);}
completion:^(BOOL finished){recognnizer.enable = YES;}];
}];
}
这种方式很好,因为它将对视图的其余副作用最小化了,不过你可能想要在动画进行时对视图禁用所有用户交互。这种情况下,你可以使用
self.view.userInteractionEnabled替换recognizer.enabled。