Search code examples
xcodeios5uiviewfadingicarousel

Fading a UIView with a subviewed button


I'm trying to create a button that fades out and then in when I open the page.

Here is the current code that i'm using, it doesn't work to fade the buttons in/ out:

- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
    if (index == 0) {
        view = [[[NSBundle mainBundle] loadNibNamed:@"nib1" owner:self options:nil] lastObject];
    }else {
        view = [[[NSBundle mainBundle] loadNibNamed:@"nib2" owner:self options:nil] lastObject];
        UIView *containView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 60, 100)];
        _btn = [UIButton buttonWithType:UIButtonTypeCustom];
        _btn.frame = CGRectMake(30, 90, 40, 30 );
        [_btn setBackgroundImage:[UIImage imageNamed:@"playButton.png"] forState:UIControlStateNormal];
        [_btn addTarget:self action:@selector(fadeButton:) forControlEvents:UIControlEventTouchUpInside];
        //[self fadeOut:_btn withDuration:1.0 andWait:1.0];
        [containView addSubview:_btn];
        [containView setAlpha:0.0];
        [view addSubview:containView];
        [UIView beginAnimations:nil context:nil];
        [containView setAlpha:1.0];
        [UIView commitAnimations];
    }
return view;
}

I've also tried using:

[UIView animateWithDuration:0.5 animations:^{_btn.alpha = 1.0;}];

None of those work. Does anyone have any tips on how to fade a subview out? Thanks


Solution

  • When you call [UIView commitAnimations], the animations are animating at the same time. When you want to animate something after an other animation try to nest animation blocks with completion:

    [UIView animateWithDuration:0.5 animations:^
    {
       //animate out
    }
    completion:^ (BOOL finished)
    {
        [UIView animateWithDuration:0.5 animations:^
        {
           //animate in
        }
        completion:^ (BOOL finished)
        {
          //Optional
        }];
    }];