2015-06-25 17 views
1

我想在默認和突出顯示的UIButton狀態之間製作一個緩慢溶解動畫。按下按鈕執行segue,並將我們帶到另一個ViewController。我已設法通過編寫的UIButton的子類有一個方法做動畫:如何正確地在狀態之間動畫UIButton?

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [UIView transitionWithView:self 
         duration:0.15 
         options:UIViewAnimationOptionTransitionCrossDissolve 
        animations:^{ self.highlighted = YES; } 
        completion:nil]; 

    [super touchesBegan:touches withEvent:event]; 
} 

然後在主視圖控制器的prepareForSegue方法寫的:

if ([sender isKindOfClass:[UIButton class]]) { 
     UIButton* button = (UIButton*)sender; 
     [UIView transitionWithView:button 
          duration:0.15 
          options:UIViewAnimationOptionTransitionCrossDissolve 
         animations:^{ button.highlighted = NO; } 
         completion:nil]; 
    } 

這種運作良好,但將單個動畫的執行劃分爲兩個文件似乎不是最好的主意。有沒有更好的方法來做到這一點?

P.S.使用在touchesEnded代碼的第二部分不工作:(

回答

2

而不是使用touchesBegantouchesEnded你可以嘗試在按鈕的控件的事件進行高亮

在你UIButton子類:

[self addTarget:self action:@selector(onTouchDown) forControlEvents:(UIControlEventTouchDown | UIControlEventTouchDragEnter)]; 
[self addTarget:self action:@selector(onTouchUp) forControlEvents:(UIControlEventTouchUpInside | UIControlEventTouchUpOutside | UIControlEventTouchDragExit | UIControlEventTouchCancel)]; 

事件方法:

-(void)onTouchDown 
{ 
    //perform your dissolve animation here 
} 

-(void)onTouchUp 
{ 
    //remove your dissolve animation here 
}