user491880
user491880

Reputation: 4869

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.

Upvotes: 8

Views: 2401

Answers (2)

kstefanou
kstefanou

Reputation: 617

Update of rob mayoff answer in swift 4:

NSAnimationContext.beginGrouping()
NSAnimationContext.current.duration = 0.5
NSAnimationContext.current.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
myView.animator().alphaValue = 0
NSAnimationContext.endGrouping()

Upvotes: 5

rob mayoff
rob mayoff

Reputation: 385540

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];

Upvotes: 17

Related Questions