天天看點

旋轉(Rotation)手勢

        UIRotationGestureRecognizer手勢識别器,就像名稱一樣,這個類能用來監聽和捕獲旋轉的手勢,能幫助你建立出更直覺的圖形使用者界面,比如一種場景,當你的應用中有一個展示圖檔的視圖,使用者需要通過旋轉圖檔來調整圖檔的方向。 

        UIRotationGestureRecognizer這個類有一個rotation的屬性,這個屬性可以用來設定旋轉的方向和旋轉的弧度。旋轉是從手指的初始位置(UIGestureRecognizerStateBegan)到最終位置(UIGestureRecognizerStateBegan)決定的。 

為了對繼承自UIView的UI元素進行旋轉,你可以将旋轉手勢識别器的rotation屬性傳遞給CGAffineTransformMakeRotation方法,以制作一個仿射轉場

//
//  ViewController.m
//  旋轉手勢
//
//  Created by Rio.King on 13-11-2.
//  Copyright (c) 2013年 Rio.King. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic,strong)UIRotationGestureRecognizer *rotationGestureRecognizer;
@property (nonatomic,strong)UILabel *helloWorldLabel;
@property (nonatomic,unsafe_unretained)CGFloat rotationAngleInRadians;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    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];
    self.rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotation:)];
    [self.view addGestureRecognizer:self.rotationGestureRecognizer];
}


-(void)handleRotation:(UIRotationGestureRecognizer *)paramSender{
    if (self.helloWorldLabel == nil) {
        return ;
    }
    
    /*take the previous rotation and add the current rotation to it */
    self.helloWorldLabel.transform = CGAffineTransformMakeRotation(self.rotationAngleInRadians
                                                                   +paramSender.rotation);
    /*at the end of the rotation, keep the angle for later use*/
    if (paramSender.state == UIGestureRecognizerStateEnded) {
        self.rotationAngleInRadians += paramSender.rotation;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
           

       在添加完如上代碼之後,我們可以根據旋轉的手勢角度給我們的這個标簽設定一個旋轉的角度,但是你可能會遇到如下問題,當一個旋轉的動作結束了,另外的一個旋轉動作又開始了,第二個旋轉的手勢角度将會把我們第一次的旋轉手勢角度給替換掉,是以在第一個旋轉動作沒有發生的時候,第二個旋轉的角度就把第一個旋轉的角度覆寫掉。是以我們需要無論這個旋轉的手勢動作什麼時候結束,我們都必須要讓目前的這次旋轉動作進行下去,是以我們就需要添加一個旋轉角度的隊列,讓我們的标簽按照這個隊列中的旋轉角度依次的進行旋轉運動。 

       我們在上面提到一個CGAffineTransformMakeRotation的方法,這個方法可用來建立依序變化的隊列。注意,在iOS SDK中所有以"CG"開都的都需要引入,CoreGraphice 架構包。

運作效果如下:

旋轉(Rotation)手勢