Search code examples
objective-cmacoscocoaanimationfade

How to fade animate hide/show window with Objective C


In Objective C, is it possible to hide my application window on launch, and then at some point of time make the call to do a pleasant fade animation to show my application window?

Not that you need to know this, but the background is that I was planning to do this from my Javascript in the webkit widget. I've already established the Objective C <==> Javascript bridge. So, when my charts finish loading, I make the call from Javascript back to Objective C to tell it to show the window with pleasant fade animation.

Here's what I've tried, but this has no fade effect -- the window just waits a sec (because those charts are loading) and then just pops on the screen fast. I tried changing the NSThread delay, but it didn't help -- that just slowed it more.

// ...in my app delegate...
- (void)applicationWillFinishLaunching:(NSNotification *)aNotification
{
    // NOTE THIS SAYS "WILL", NOT "DID" -- VERY IMPORTANT.
    // TO DO OTHERWISE WOULD GIVE YOU A WINDOW FLASH FOR A SECOND,
    // THEN FADE IN.
    [self hideWindow:_window];
}

- (void)hideWindow:(NSWindow *)window
{
    float alpha = 0.0;
    [window setAlphaValue:alpha];
    [window makeKeyAndOrderFront:self];
}

- (void)showWindow:(NSWindow *)window
{
    float alpha = 1.0;
    [window setAlphaValue:alpha];
    [window makeKeyAndOrderFront:self];
}

- (void)fadeOutWindow:(NSWindow*)window
{
    float alpha = 1.0;
    [window setAlphaValue:alpha];
    [window makeKeyAndOrderFront:self];
    for (int x = 0; x < 10; x++) {
        alpha -= 0.1;
        [window setAlphaValue:alpha];
        [NSThread sleepForTimeInterval:0.020];
    }
}

- (void)fadeInWindow:(NSWindow*)window
{
    float alpha = 0.0;
    [window setAlphaValue:alpha];
    [window makeKeyAndOrderFront:self];
    for (int x = 0; x < 10; x++) {
        alpha += 0.1;
        [window setAlphaValue:alpha];
        [NSThread sleepForTimeInterval:0.020];
    }
}

// My javascript to ObjC bridge calls this:
- (void)callShowAppWindow;
{
    [self fadeInWindow:_window];
}

Solution

  • In my source on the question, I almost had it. Here's the fix on two functions that causes the fade effect:

    - (void)fadeOutWindow:(NSWindow*)window
    {
        float alpha = 1.0;
        [window setAlphaValue:alpha];
        [window makeKeyAndOrderFront:self];
        [NSAnimationContext beginGrouping];
        [[NSAnimationContext currentContext] setDuration:1.5f];
        [[window animator] setAlphaValue:0.f];
        [NSAnimationContext endGrouping];
    }
    
    - (void)fadeInWindow:(NSWindow*)window
    {
        float alpha = 0.0;
        [window setAlphaValue:alpha];
        [window makeKeyAndOrderFront:self];
        [NSAnimationContext beginGrouping];
        [[NSAnimationContext currentContext] setDuration:1.5f];
        [[window animator] setAlphaValue:1.f];
        [NSAnimationContext endGrouping];
    }