Search code examples
objective-ccocoaanimationuikit

How to do UIView style animations in Cocoa/Mac app development


I'm making the transition from programming iPhone to native Mac applications. One part that I miss is the simplicity of the UIView animation system.

I had the following two methods for a UIView subclass:

-(void) hide{
    _isHidden=YES;
    [UIView commitAnimations];
    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.5];  
    self.alpha = 0;
    [UIView commitAnimations];
}
-(void) show{
    _isHidden=NO;
    [UIView commitAnimations];
    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.5];  
    self.alpha = 1;
    [UIView commitAnimations];    
}

Now I'm not sure how to accomplish this in Cocoa. I tried the following but I'm not sure it works as it should.

-(void) hide{
    [[_myView animator] setAlpha:0];
}

I call this function (hide) multiple times sometimes while the fade function might still be running.


Solution

  • This should produce the same result as your iOS code:

    [NSAnimationContext beginGrouping]; {
        [[NSAnimationContext currentContext] setDuration:.5];
        [[NSAnimationContext currentContext] setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
        [_myView.animator setAlphaValue:0.0];
    } [NSAnimationContext endGrouping];
    

    The default duration is .25 seconds. I'm not sure what the default timing function is. If you're ok with the defaults, you can just say this:

    [_myView.animator setAlphaValue:0.0];