UIRotationGestureRecognizer 能監聽並捕獲使用者在螢幕上以雙指進行的旋轉動作。它提供了一個 rotation 屬性,用來取得本次手勢旋轉的弧度;而在手勢的生命週期中,我們通常會關注兩個狀態:UIGestureRecognizerStateBegan 代表手勢開始,UIGestureRecognizerStateEnded 代表手勢結束。本文就示範如何用它來旋轉一個 UILabel。
ZYViewController.m:
// rotationGestureRecognizer 是旋轉手勢的監聽實例
@synthesize rotationGestureRecognizer;
@synthesize helloWorldLabel;
@synthesize rotationAngleInRadians;
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
/****** 建立 Label 元件 start ******/
self.helloWorldLabel = [[UILabel alloc] initWithFrame:CGRectZero];
self.helloWorldLabel.text = @"Hello, World!";
self.helloWorldLabel.font = [UIFont systemFontOfSize:16.0f];
[self.helloWorldLabel sizeToFit]; // 依文字內容自動調整尺寸
self.helloWorldLabel.center = self.view.center;
[self.view addSubview:self.helloWorldLabel];
/****** 建立 Label 元件 end ******/
// 建立旋轉手勢識別器
self.rotationGestureRecognizer =
[[UIRotationGestureRecognizer alloc] initWithTarget:self
action:@selector(handleRotations:)];
[self.view addGestureRecognizer:self.rotationGestureRecognizer];
}
- (void) handleRotations:(UIRotationGestureRecognizer *)paramSender{
if (self.helloWorldLabel == nil) { return; }
// 把「之前累積的弧度」與「本次手勢的弧度」相加後套用旋轉
// rotationAngleInRadians 用來保存累積的旋轉量,
// 每次手勢結束時更新它,記住上一次的姿態
self.helloWorldLabel.transform =
CGAffineTransformMakeRotation(self.rotationAngleInRadians + paramSender.rotation);
// 手勢結束時,把本次旋轉量累加進去
if (paramSender.state == UIGestureRecognizerStateEnded) {
self.rotationAngleInRadians += paramSender.rotation;
}
}
這裡最容易忽略的細節就是 rotationAngleInRadians 這個變量。UIRotationGestureRecognizer 回報的 rotation 是「本次手勢相對上一次的增量」,而不是絕對角度。如果直接把增量套上去,手指一放開再重新旋轉,標籤就會跳回接近零度的位置。用一個變量把每次結束時的旋轉量累加保存,才能做到連續多次旋轉都自然銜接。
初始狀態:
旋轉之後(在模擬器中按住 Option 鍵並按下滑鼠左鍵,畫面上會出現兩個小圓點,拖動即可模擬旋轉手勢):
以上就是捕獲旋轉手勢的完整流程。同样的思路也適用於縮放(UIPinchGestureRecognizer)與拖動(UIPanGestureRecognizer)——差別只在於狀態如何累積,希望對大家有所幫助。