How to give NSWindow a shake effect as saying NO, as in Login failure window

cocoa, macos, nswindow, objective-c

Solution

You need to add the `QuartzCore Framework`.

Then use the following :

#import <Quartz/Quartz.h>


//below action calls the method `shakeWindow`

- (IBAction)shake:(id)sender {
    [self shakeWindow];
}

-(void)shakeWindow{

    static int numberOfShakes = 3;
    static float durationOfShake = 0.5f;
    static float vigourOfShake = 0.05f;

    CGRect frame=[self.window frame];
    CAKeyframeAnimation *shakeAnimation = [CAKeyframeAnimation animation];

    CGMutablePathRef shakePath = CGPathCreateMutable();
    CGPathMoveToPoint(shakePath, NULL, NSMinX(frame), NSMinY(frame));
    for (NSInteger index = 0; index < numberOfShakes; index++){
        CGPathAddLineToPoint(shakePath, NULL, NSMinX(frame) - frame.size.width * vigourOfShake, NSMinY(frame));
        CGPathAddLineToPoint(shakePath, NULL, NSMinX(frame) + frame.size.width * vigourOfShake, NSMinY(frame));
    }
    CGPathCloseSubpath(shakePath);
    shakeAnimation.path = shakePath;
    shakeAnimation.duration = durationOfShake;

    [self.window setAnimations:[NSDictionary dictionaryWithObject: shakeAnimation forKey:@"frameOrigin"]];
    [[self.window animator] setFrameOrigin:[self.window frame].origin];

}

Problem

I use below code for shake a view and it works properly,now i want to shake a window i change two line that i bolded in code with code2 but doesn't work ``` //-------- code 1 CGFloat DegreesToRadians(CGFloat degrees) { return degrees * M_PI / 180; } NSNumber* DegreesToNumber(CGFloat degrees) { return [NSNumber numberWithFloat: DegreesToRadians(degrees)]; } --------------- [self.view setWantsLayer:YES]; CAKeyframeAnimation * animation= [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"]; [animation setDuration:0.04]; [animation setRepeatCount:10]; srand([[NSDate date] timeIntervalSince1970]); float rand = (float)random(); [animation setBeginTime:CACurrentMediaTime() + rand * .0000000001]; NSMutableArray *values = [NSMutableArray array]; [values addObject:DegreesToNumber(-1)]; [values addObject:DegreesToNumber(1)]; [values addObject:DegreesToNumber(-1)]; [animation setValues:values]; [self.view.layer addAnimation:animation forKey:@"rotate"]; //-------- code 2 [self.window.animator addAnimation:animation forKey:@"rotate"]; [self.window.animator setWantsLayer:YES]; ```

Original source