iOS手勢操作總結
手勢操作種類
手勢操作的代理方法(UIGestureRecognizerDelegate)
手勢可能發生的條件,返回NO可以阻止此手勢的發生或者此手勢不產生任何效果
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer;是否允許多個手勢同時發生
- (BOOL)gestureRecognizer:(UIGestureRecognizer *) gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer: (UIGestureRecognizer *)otherGestureRecognizer;UITapGestureRecognier敲擊,點擊手勢
UILongPressGestureRecongnizer長按
UIPinchGestureRecognizer縮放手勢
scale: 設置縮放比例,相對於原來大小
UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinch:)]; // 代理 pinch.delegate = self; // 設置縮放比例 pinch.scale = 1.2; [self.image addGestureRecognizer:pinch];UIRotationGestureRecognizer旋轉手勢
rotation: 旋轉弧度,要保證每次都在上一次位置開始旋轉,而不是回歸初始位置,必須要在動作方法裡將此值清零
- (void)setupRotation { UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotation:)]; // 設置代理 rotation.delegate = self; [self.image addGestureRecognizer:rotation]; } - (void)rotation:(UIRotationGestureRecognizer *)rotation { // 旋轉角度 CGFloat radian = rotation.rotation; self.image.transform = CGAffineTransformRotate(self.image.transform, radian); // 復位,保證每次都是在上一次位置開始轉,而不是每次都回歸初始位置再轉 rotation.rotation = 0; }UISwipeGestureRecognizer輕掃, 手指按下然後在屏幕上滑動
輕掃分四個方向(上下左右),並且如果要在一個控件上同時添加一個以上的輕掃動作,必須對每個動作添加一個對象。也就是說每個方向的動作對應一個對象。
direction: 指定輕掃動作的方向
typedefNS_OPTIONS(NSUInteger, UISwipeGestureRecognizerDirection) { UISwipeGestureRecognizerDirectionRight = 1 << 0,// 從左向右 UISwipeGestureRecognizerDirectionLeft = 1 << 1,// 從右向左 UISwipeGestureRecognizerDirectionUp = 1 << 2,// 從下往上 UISwipeGestureRecognizerDirectionDown = 1 << 3// 從上往下 }; UISwipeGestureRecognizer *swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe:)]; // 設置代理 swipeUp.delegate = self; // 修改方向, 從下往上 swipeUp.direction = UISwipeGestureRecognizerDirectionUp; [self.image addGestureRecognizer:swipeUp]; // 添加其他方向手勢 UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe:)]; // 修改方向, 從下往上 swipeDown.direction = UISwipeGestureRecognizerDirectionDown; [self.image addGestureRecognizer:swipeDown];UIPanGestureRecognizer拖拽,按下拖動控件操作
注意點:手勢的觸摸點locationInView和手勢的移動點translationInView是不一樣的,前者是用locationInView取得是指手指在當前控件中的坐標,後者表示相對於父view的rect
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)]; // 設置代理 pan.delegate = self; [self.image addGestureRecognizer:pan]; // 手勢的觸摸點 // CGPoint p = [pan locationInView:self.image]; // 手勢的移動點(每次移動的位移點) CGPoint transP = [pan translationInView:self.image]; NSLog(@"%f, %f", transP.x, transP.y); self.image.transform = CGAffineTransformTranslate(self.image.transform, transP.x, transP.y); // 復位 [pan setTranslation:CGPointZero inView:self.image];