William T.
William T.

Reputation: 14331

How to add subview with flip animation?

If you create a brand new single view app and put this code behind a button:

UIView *blah = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
blah.backgroundColor = [UIColor grayColor];
[UIView transitionWithView:blah duration:1
                   options:UIViewAnimationOptionTransitionFlipFromRight
                animations:^{
                    [self.view addSubview:blah];
                }
                completion:^(BOOL finished){

                }];

The subview is added immediately with no animation. If you add the subview first then try to animate it... you get the same problem.

    UIView *blah = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
    [self.view addSubview:blah];
    [UIView transitionWithView:blah duration:1
                       options:UIViewAnimationOptionTransitionFlipFromRight
                    animations:^{
                        blah.backgroundColor = [UIColor grayColor];
                    }
                    completion:^(BOOL finished){

                    }];

How on Earth do you animate a flip for a subview while or immediately after adding it?

Upvotes: 6

Views: 9152

Answers (2)

Rob
Rob

Reputation: 437442

You generally need to have the container that constrains the animation to be in place already:

- (void)viewDidLoad
{
    [super viewDidLoad];

    CGRect frame = CGRectMake(0, 0, 100, 100);

    _container = [[UIView alloc] initWithFrame:frame];
    _container.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:_container];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    UIView *subview = [[UIView alloc] initWithFrame:_container.bounds];
    subview.backgroundColor = [UIColor darkGrayColor];

    [UIView transitionWithView:_container
                      duration:1.0
                       options:UIViewAnimationOptionTransitionFlipFromRight
                    animations:^{
                        [_container addSubview:subview];
                    }
                    completion:NULL];
}

Upvotes: 12

guenis
guenis

Reputation: 2538

This is worth a try:

UIView *blah = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
blah.backgroundColor = [UIColor grayColor];
[self.view addSubview:blah];
blah.alpha = 0.0; //Or with blah.hidden = TRUE and then FALSE inside the animation block
[UIView transitionWithView:blah
                  duration:1
                   options:UIViewAnimationOptionTransitionFlipFromRight
                animations:^{
                     blah.alpha = 1.0;
                }
                completion:^(BOOL finished){

                }];

Upvotes: 1

Related Questions