如何使在Objective-C的动画视图震动?

问题描述:

我有一个名为qShake的UIView。当用户作出了错误,我希望该视图动摇从左至右在很小的空间的时间短的时间。我将如何创建一个动画来做到这一点?

I have a UIView called qShake. When the user makes an error, I want that view to shake from left to right in a small space for a short period of time. How would I create an animation to do that?

您可以使用CABasicAnimation,并设置重复次数为一些小的价值,同时动画要振动view.layer的位置。需要注意的是 clipsToBounds 的视图必须设置为NO。此外,一定要包括该项目的QuartzCore框架。

You can use a CABasicAnimation, and set the repeat count to some small value, while animating the position of the view.layer that you want to vibrate. Note that clipsToBounds for the view must be set to NO. Also be sure to include the QuartzCore framework in the project.

- (void)shakeView:(UIView *)view
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.x"];
    animation.duration = 0.1;
    animation.byValue = @(20);
    animation.autoreverses = YES;
    animation.repeatCount = 10;
    [view.layer addAnimation:animation forKey:@"Shake"];
}