Search code examples
objective-ccocoacore-animationnsview

Making fading effect with NSView


I have a subview which I want to show up to make a dissolve fade effect. For that purpose, I'm trying to:

  1. Show it
  2. Fade it

For that purpose, I set a "showFade" method on my superview (Fader is the subview defined previously. someImage is already defined).

- (void)showFade {

  [Fader setHidden:NO];
  [Fader setImage: someImage];
  [[Fader animator] setHidden:YES];

}

The problem is: it works for the first time, and the subview fades, but it never shows up again. What am I doing wrong?

EDIT: As requested, here is a more complete sample of the code

- (void)awakeFromNib {

  Fader = [[NSImageView alloc] initWithFrame: [self bounds]];
  Images[0] = @"Tower";
  Images[1] = @"Desert";
  Images[2] = @"Fall";
  image = 0;

  [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(showFader:) userInfo:nil repeats:YES];
  [self addSubview: Fader];
  [self nextImage];
  [super awakeFromNib];

}

- (void)showFader: (NSTimer*)timer {

  [Fader setImage: [self image]];
  [Fader setHidden:NO];
  [[Fader animator] setHidden:YES];

  [self nextImage];

}

- (void)nextImage {
  if (image == 2) {
    image = 0;
  }
  else {
    image++;
  }

  [self setImage: [NSImage imageNamed: Images[image]]];

}

So, basically, I have a repeating timer making the parent NSImageView to loop between an array of images and making the "Fader" to show up with the previous image and fade out. The problem is that it only shows up once.


Solution

  • I had the same problem a long time ago (yet I never solved it), but I think this could have something to do with the fact that you ask your view to be showed and dissolved in the same event loop.

    I guess you should let the event loop make an iteration (so that your view is actually displayed) before asking to dissolve the view. I guess you could do it by setting a (short) timer that would fire a couple of millisecs after the view is displayed (by setHidden:NO). I also guess there are easier ways to solve the problem (and I would be glad to hear them).

    What is more, you could also try animator setAlphaValue:0.0 to have a smooth transition.

    I am not definitely not sure I have a correct answer, that's only a suggestion...