建立一個 UIRotationGestureRecognizer 並綁定到視圖上,就能捕獲使用者以雙指轉動的手勢。這個類別有一個 rotation 屬性,代表本次旋轉的弧度;手勢開始與結束分別對應 UIGestureRecognizerStateBegan 與 UIGestureRecognizerStateEnded 兩個狀態。
// 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; }
// 將先前累積的弧度與本次旋轉弧度相加後套用,
// 如此連續多次旋轉才能接續累積,不會每次都被重置
self.helloWorldLabel.transform =
CGAffineTransformMakeRotation(self.rotationAngleInRadians + paramSender.rotation);
// 手勢結束時把本次弧度存下來
if (paramSender.state == UIGestureRecognizerStateEnded){
self.rotationAngleInRadians += paramSender.rotation;
}
}
旋轉前
旋轉後(模擬器中按住 Option 鍵並拖曳滑鼠,出現兩個小圓點後即可轉動)
這是旋轉手勢最容易出錯的地方。paramSender.rotation 只代表本次手勢區間內的相對旋轉量,手勢一結束就歸零。如果直接把 rotation 套進 CGAffineTransformMakeRotation,第二次旋轉時視圖會突然跳回接近 0 弧度的角度。
解法就是自己維護一個累積值:每次手勢結束時把 rotation 加進去,下次開始時再疊加上去,視覺上就成為連續、可累積的旋轉。這個模式在縮放、位移手勢上同樣適用。