views:

51

answers:

1

I have a method in my UIView subclass "Card" to dismiss an instance by fading its alpha from 1 to 0. I do a similar thing when I add the card to the superview and it fades in fine. But when I call fadeAway, it just disappears immediately. The presentation code is in my controller class. Here is my Card.h and Card.m


#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@class Card;

@interface Card : UIView {

 int            upperOperand;
    int         lowerOperand;
    NSString*   theOperator;
    int         theResult;
}

@property(nonatomic) int upperOperand;
@property(nonatomic) int lowerOperand;
@property(nonatomic, retain) NSString* theOperator;
@property(nonatomic) int theResult;

- (void)fadeAway;

@end

#import "Card.h"

@implementation Card

@synthesize upperOperand;
@synthesize lowerOperand;
@synthesize theOperator;
@synthesize theResult;

- (void)fadeAway {
    self.alpha = 1.0f;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:2.0f];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    self.alpha = 0.0f;
    [UIView commitAnimations];  

    [self removeFromSuperview];
}

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        // Initialization code
        self.backgroundColor = [UIColor redColor];
        self.layer.cornerRadius = 15;
        self.alpha = 1.0;
        self.layer.borderColor = [[UIColor blueColor] CGColor];
        self.layer.borderWidth = 4;
    }
    return self;

   - (void)dealloc {
    [super dealloc];
}

@end

+1  A: 

Since you're removing self from its superview immediately, I don't think it ever has a chance to perform the animation.

You might want to look into setAnimationDidStopSelector:. There's a discussion on this here: http://stackoverflow.com/questions/404957/animation-end-callback-for-calayer

Another idea is to delay the removal of the subview. For example,

[self performSelector:@selector(removeFromSuperview) 
    withObject:nil 
    afterDelay:2.0f];
Kalle
Are you saying that the [UIView commitAnimations] line just _starts_ the animation and that it immediately goes on to the next line and removes it? That would make sense to me. I've seen that setAnimationDidStopSelector: before, but not tried to use it yet. I assume that means another method - one to do the animation and one to remove the view when it's done, right?
Steve
I think Kalle's answer is correct, defer your cleanup to the animationDidStopselector:.
Elfred
Exactly. That, or you can delay the removal with a delay that matches the animation. I updated my answer above to include an example of this method.
Kalle
Thanks again - I used the setAnimationDidStopSelector: and it works like a charm! Getting these animations to work is highly satisfying - really dresses up the program.
Steve