有些時候,我們並不特別需要知道iPhone傾斜的角度,而是單純想偵測使用者是否晃動iPhone,比方像App LINE一樣利用晃動來和鄰近的陌生人交朋友。接下來,彼得潘將繼續以可愛的紅茶做主角,拍攝翻滾吧,紅茶,每當我們晃動iPhone,紅茶的特寫圖片即優雅地旋轉15度角。
(1) 建立Single View Application專案ShakeTest。
(2) 新增連結至紅茶圖片的dogImageView和儲存圖片旋轉角度的rotateDegree。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface ShakeTestViewController : UIViewController | |
{ | |
__weak IBOutlet UIImageView *dogImageView; | |
float rotateDegree; | |
} |
(3) 開啟ShakeTestViewController成為first responder的能力。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(BOOL)canBecomeFirstResponder | |
{ | |
return YES; | |
} |
說明:
想要讓ShakeTestViewController能夠偵測到iPhone的晃動,就好像想看到鬼般,必須先啟動某個開關。只要打開陰陽眼,我們就可以看到鬼。不過這實在太危險了,我們還是打開偵測晃動的開關就好。在iOS的國度裡,只有兩種物件遺傳偵測晃動的血液,一個是UIView,一個是UIViewController。但除此之外,還必須成為first responder才能真正偵測到晃動。由於view
controller預設將成為first responder的能力封印起來,因此我們得先覆寫canBecomeFirstResponder,回傳YES解除封印。另外在我們的例子裡,由於沒有其它物件和ShakeTestViewController搶,所以它當然而然成為first responder的不二人選,否則在多人競爭的環境,我們還必另針對欲偵測晃動的對象呼叫becomeFirstResponder。
(4) 定義晃動發生時觸發的method motionEnded: withEvent:。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event | |
{ | |
if(motion == UIEventSubtypeMotionShake) | |
{ | |
rotateDegree = rotateDegree + 15; | |
dogImageView.transform = | |
CGAffineTransformMakeRotation(2*M_PI*rotateDegree/360); | |
} | |
} |
說明:
1. -(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
當晃動發生時,此method將被呼叫。
2. if(motion == UIEventSubtypeMotionShake)
目前當此method被呼叫時,傳入的motion其實一定是UIEventSubtypeMotionShake,不過為了保險起見,我們還是做個比對,確定真的是晃動。
3. dogImageView.transform =
CGAffineTransformMakeRotation(2*M_PI*rotateDegree/360);
利用CGAffineTransformMakeRotation將圖片順時針旋轉。rotateDegree為旋轉的角度,在這個例子裡,每晃動一次,我們即旋轉15度。(一圈是360度。)
執行App:
為了夢想,盡情地翻滾吧,紅茶!
沒有留言:
張貼留言