UIView shake animation

后端 未结 16 1277
梦毁少年i
梦毁少年i 2020-11-28 18:07

i\'m trying to make a UIView shake when a button is pressed.

I am adapting the code I found on http://www.cimgf.com/2008/02/27/core-animation-tutorial-window-shake-e

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 18:38

    You can try this piece of code:

    to call the code below, use: [self earthquake:myObject];

    #pragma mark EarthQuake Methods
    
    - (void)earthquake:(UIView*)itemView
    {
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); 
    
        CGFloat t = 2.0;
    
        CGAffineTransform leftQuake  = CGAffineTransformTranslate(CGAffineTransformIdentity, t, -t);
        CGAffineTransform rightQuake = CGAffineTransformTranslate(CGAffineTransformIdentity, -t, t);
    
        itemView.transform = leftQuake;  // starting point
    
        [UIView beginAnimations:@"earthquake" context:itemView];
        [UIView setAnimationRepeatAutoreverses:YES]; // important
        [UIView setAnimationRepeatCount:3];
        [UIView setAnimationDuration:0.05];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(earthquakeEnded:finished:context:)];
    
        itemView.transform = rightQuake; // end here & auto-reverse
    
        [UIView commitAnimations];
    }
    
    - (void)earthquakeEnded:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context 
    {
        if ([finished boolValue]) 
        {
            UIView* item = (UIView *)context;
            item.transform = CGAffineTransformIdentity;
       }
    }
    

提交回复
热议问题