2013-04-25 34 views
3

我一直在嘗試使用下面的方法旋轉按鈕:旋轉的UIButton

-(IBAction)rotate:(id)sender{ 
    CGPoint pencilCenter = pencil.center; 
    [pencil setCenter:pencilCenter]; 
    CGFloat floater = 1.0; 
    [UIView animateWithDuration:0.7 animations:^(void){ 
     [pencil setTransform:CGAffineTransformMakeRotation(floater)]; 
    }]; 
    [UIView animateWithDuration:0.7 animations:^(void){ 
     [pencil setTransform:CGAffineTransformMakeRotation(floater)]; 
    }]; 
} 

據說這是爲了使按鈕做某種「動搖」,那麼它應該能回到原來的位置 - 但它所做的只是改變按鈕的位置,將其移到僅一側,而在另一次運行該方法時按鈕不會對產生反應

我的代碼有什麼問題?

謝謝!

編輯2: 我的問題是 - 我該如何做一個按鈕來做一些動作/擺動,例如,編輯spboardboard時擺動應用程序模式。

使用此代碼給我旋轉到左側,從左到右然後從右到左平滑動畫,然後旋轉到原始位置。現在,我希望這不是僅僅旋轉,而是用動畫來完成,就像擺動一樣。

[UIView animateWithDuration:0.25 
         delay:0.0 
        options:(UIViewAnimationOptionAllowUserInteraction | UIViewAnimationCurveLinear | UIViewAnimationOptionAutoreverse) 
       animations:^ { 
        pencil.transform = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(30)); 
        pencil.transform = CGAffineTransformIdentity; 
       } 
       completion:^(BOOL finished){ 
       } 
]; 

謝謝!

+1

爲什麼你在同一時間以相同的旋轉量開始2個動畫? – Wain 2013-04-25 17:01:29

+1

請確切地說明你的意思是「只將它移動到一邊」。也許張貼一些模擬器的截圖? – David 2013-04-25 17:04:47

+1

你可以嘗試下面的帖子,它的UIView,但你可以將其應用於UIButton http://stackoverflow.com/questions/929364/how-to-create-iphones-wobbling-icon-effect – 2013-04-25 17:10:37

回答

1

嘗試使用CGAffineTransformRotate而不是CGAffineTransformMakeRotation。您可以在所有調用中使用`CGAffineTransformIdentity1作爲第一個參數,因此根據第二個參數進行的最終轉換將應用於框架的原始形狀(?)。

0

那麼,docs說:「...指定的動畫立即開始在另一個線程...」。現在,所有的UIKit代碼都不是線程安全的。所以,如果不是從完成塊(在單獨的線程中運行)調用你的UI setter(setTransform,setCenter)來使用performSelectorOnMainThread:withObject:來調用它們,也許會有幫助。

+1

設置視圖屬性在動畫中動畫塊是動畫塊的全部點。您從文檔中得出了錯誤的結論。 – jrturton 2013-04-26 06:42:53

+0

@jrturton:你說得對!感謝您指出。 – 2013-04-26 06:56:31

6

導入「QuartzCore/QuartzCore.h」,並嘗試這個,

CABasicAnimation *fullRotation; 
fullRotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; 
fullRotation.delegate = self; 
fullRotation.fromValue = [NSNumber numberWithFloat:0]; 
fullRotation.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)]; 
fullRotation.duration = 1.7; 
fullRotation.repeatCount = 2; 
[btnTemp.layer addAnimation:fullRotation forKey:@"360"]; 
+0

我的意思是做一個小小的擺動,而不是一個完整的旋轉...... – 2013-04-29 18:29:42

1

雖然它沒有完全回答這個問題,Shardul的答案是偉大旋轉按鈕(2個完整旋轉)。所以這裏,轉換爲斯威夫特3

let fullRotation = CABasicAnimation(keyPath: "transform.rotation") 
fullRotation.delegate = self 
fullRotation.fromValue = NSNumber(floatLiteral: 0) 
fullRotation.toValue = NSNumber(floatLiteral: Double(CGFloat.pi * 2)) 
fullRotation.duration = 0.5 
fullRotation.repeatCount = 2 
button.layer.add(fullRotation, forKey: "360") 

您將需要進口QuartzCore:

import QuartzCore 

和你的ViewController需要順應CAAnimationDelegate:

class ViewController: UIViewController, CAAnimationDelegate { 

}