Search code examples
objective-cmacosanimationnsbutton

NSButton grow-shrink animation in Cocoa macOS application in Objective-C


I am having a mac app in Objective-C.

In which, I want my button to animate like grow after some seconds.

I couldn't find anything in Cocoa application.

[UIView beginAnimations:nil context:NULL];
CGRect pos=v2.bounds;
pos.size.height=500;
pos.size.width=500;
[UIView setAnimationDuration:1.0];

[UIView setAnimationRepeatCount:15];
[UIView setAnimationRepeatAutoreverses:YES];
v2.bounds=pos;
[UIView commitAnimations];

I used the above code in ios to grow a button but how to make this happen in cocoa mac application?

So basically I want a grown and shrink animation of an NSButton.


Solution

  • In cocoa you have a several ways of animations, you probably need to chose an appropriate for you. For instance you can use NSAnimationContext for this task with a code like this:

    - (IBAction)buttonPressed:(id)sender {
        [self runAnimations:10];
    }
    
    - (void)runAnimations:(NSUInteger)repeatCount {
    
        CGFloat oldWidth = self.buttonWidthConstraint.constant;
        CGFloat oldHeight = self.buttonHeightConstraint.constant;
    
        [NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
            context.duration = 1.;
            self.buttonWidthConstraint.animator.constant = 500;
            self.buttonHeightConstraint.animator.constant = 500;
        } completionHandler:^{
                //change back to original size
                [NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
                    context.duration = 1.;
                    self.buttonWidthConstraint.animator.constant = oldWidth;
                    self.buttonHeightConstraint.animator.constant = oldHeight;
                } completionHandler:^{
                    if (repeatCount - 1 > 0) {
                        [self runAnimations:repeatCount - 1];
                    }
                }];
        }];
    }
    

    It is much better to animate a constraints neither operating with bounds directly. But if you really need to - you can adopt this code to whatever you want.

    A great video about all the options you have on OSX for animations may be seen in WWDC 2013, Best Practices for Cocoa Animation, I encourage you to watch it completely.