Search code examples
iosuiviewtransitionviewflipper

UIView Flip transition not working


recently I am doing some project on something like a flip card. I have two subviews inside the view controller and I would like to flip over the subview on click of a button. What I can achieve now is the whole view is flipping but I just want the subview ONLY =( Please let me know what wrong with my code.....;( Thanks guys

- (void)test: (id)sender{
[UIView transitionFromView:firstView
                    toView:secondView
                  duration:0.5f
                   options:UIViewAnimationOptionTransitionFlipFromRight
                completion:^(BOOL finished){
                    /* do something on animation completion */
                }];

}

- (void)viewDidLoad
{
   [super viewDidLoad];
   firstView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 250, 250)];
   secondView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 250, 250)];
   firstView.backgroundColor = [UIColor redColor];
   secondView.backgroundColor = [UIColor blueColor];
   UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
   button.frame = CGRectMake(0, 0, 25, 25);
   [button addTarget:self action:@selector(test:)forControlEvents:UIControlEventTouchUpInside];
   [self.view addSubview:button];
   [self.view addSubview:secondView];
   [self.view addSubview:firstView];
}

Solution

  • Add a another view (I call it container) to self.view, and add the firstView to that instead of directly to self.view. You don't need to add the second view at all -- the transition does that for you.

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        UIView *container = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 250, 250)];
        firstView = [[UIView alloc] initWithFrame:CGRectMake(0,0, 250, 250)];
        secondView = [[UIView alloc] initWithFrame:CGRectMake(0,0, 250, 250)];
        firstView.backgroundColor = [UIColor redColor];
        secondView.backgroundColor = [UIColor blueColor];
        UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        button.frame = CGRectMake(0, 0, 25, 25);
        [button addTarget:self action:@selector(test:)forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        [container addSubview:firstView];
        [self.view addSubview:container];
    }