2014-04-29 38 views
1

我有一個有兩種狀態的按鈕(我使用「選擇」狀態來切換按鈕)。當用戶點擊按鈕時,我想動畫狀態之間的轉換。在狀態之間向UIButton添加動畫

我有一個形成動畫的圖像列表 - 將動畫添加到按鈕的邏輯是什麼?

回答

2

子類的UIButton,重寫setSelected方法是這樣的:

-(void)setSelected:(BOOL)selected{ 
    self.enabled = NO; // disable btn until animation finished 
    [self setBackgroundImage:nil forState:UIControlStateNormal]; 
    [self setBackgroundImage:nil forState:UIControlStateSelected]; 

    NSArray *imageNames; 

    // hardcoded frames sequences is for clarity ofcourse =) 
    if (selected){ 
     // direct frames sequence 
     imageNames = @[@"normalBG", @"frame0", @"frame1", @"frame2", @"selectedBG"]; 
    } else { 
     // reversed frames sequence 
     imageNames = @[@"selectedBG", @"frame2", @"frame1", @"frame0", @"normalBG"]; 
    } 
    NSTimeInterval animationDuration = (float)imageNames.count/YOUR_ANIMATION_FPS; 

    NSMutableArray *imageBuffer = [NSMutableArray arrayWithCapacity:imageNames.count]; 
    NSMutableArray *timeBuffer = [NSMutableArray arrayWithCapacity:imageNames.count]; 

    [imageNames enumerateObjectsUsingBlock:^(NSString *name, NSUInteger idx, BOOL *stop) { 
     [imageBuffer addObject:(__bridge id)[UIImage imageNamed:name].CGImage]; 
     [timeBuffer addObject:@((float)(idx)/(imageNames.count-1))]; 
    }]; 

    NSArray *images = [NSArray arrayWithArray:imageBuffer]; 
    NSArray *times = [NSArray arrayWithArray:timeBuffer]; 
    imageBuffer = nil; 
    timeBuffer = nil; 


    CAKeyframeAnimation *framesAnimation = [CAKeyframeAnimation animationWithKeyPath:@"contents"]; 
    framesAnimation.values = images; 
    framesAnimation.keyTimes = times; 
    framesAnimation.calculationMode = kCAAnimationLinear; 
    framesAnimation.removedOnCompletion = YES; 
    framesAnimation.fillMode = kCAFillModeForwards; 
    framesAnimation.duration = animationDuration; 


    [CATransaction begin]; 
    [CATransaction setCompletionBlock:^{ 
     [super setSelected:selected]; 
     if (selected){ 
      [self setBackgroundImage:[UIImage imageNamed:@"selectedBG"] forState:UIControlStateSelected]; 
      [self setBackgroundImage:nil forState:UIControlStateNormal]; 
     } else { 
      [self setBackgroundImage:nil forState:UIControlStateSelected]; 
      [self setBackgroundImage:[UIImage imageNamed:@"normalBG"] forState:UIControlStateNormal]; 
     } 
     self.enabled = YES; 
    }]; 
    [self.layer addAnimation:framesAnimation forKey:@"contents"]; 
    [CATransaction commit]; 
} 

不要忘記設置初始背景圖像,即,在按鈕的init方法[self setBackgroundImage:[UIImage imageNamed:@"normalBG"] forState:UIControlStateNormal];