欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

IOS手势操作(拖动、捏合、旋转、点按、长按、轻扫、自定义)

程序员文章站 2022-03-08 16:25:15
下面通过图文并茂的方式给大家分享下ios手势操作(拖动、捏合、旋转、点按、长按、轻扫、自定义)的相关内容。 1、uigesturerecognizer 介绍 手势识别在...

下面通过图文并茂的方式给大家分享下ios手势操作(拖动、捏合、旋转、点按、长按、轻扫、自定义)的相关内容。

1、uigesturerecognizer 介绍
手势识别在 ios 中非常重要,他极大地提高了移动设备的使用便捷性。

ios 系统在 3.2 以后,他提供了一些常用的手势(uigesturerecognizer 的子类),开发者可以直接使用他们进行手势操作。

uipangesturerecognizer(拖动)

uipinchgesturerecognizer(捏合)

uirotationgesturerecognizer(旋转)

uitapgesturerecognizer(点按)

uilongpressgesturerecognizer(长按)

​uiswipegesturerecognizer(轻扫)

另外,可以通过继承 uigesturerecognizer 类,实现自定义手势(手势识别器类)。

ps:自定义手势时,需要 #import <uikit/uigesturerecognizersubclass.h>,一般需实现如下方法:

复制代码 代码如下:

- (void)reset;

- (void)touchesbegan:(nsset *)touches withevent:(uievent *)event;
- (void)touchesmoved:(nsset *)touches withevent:(uievent *)event;
- (void)touchesended:(nsset *)touches withevent:(uievent *)event;
- (void)touchescancelled:(nsset *)touches withevent:(uievent *)event;
//以上方法在分类 uigesturerecognizer (uigesturerecognizerprotected) 中声明,更多方法声明请自行查看

uigesturerecognizer 的继承关系如下:

IOS手势操作(拖动、捏合、旋转、点按、长按、轻扫、自定义)

2、手势状态
在六种手势识别中,只有一种手势是离散型手势,他就是 uitapgesturerecognizer。

离散型手势的特点就是:一旦识别就无法取消,而且只会调用一次手势操作事件(初始化手势时指定的回调方法)。

​换句话说其他五种手势是连续型手势,而连续型手势的特点就是:会多次调用手势操作事件,而且在连续手势识别后可以取消手势。从下图可以看出两者调用操作事件的次数是不同的:

IOS手势操作(拖动、捏合、旋转、点按、长按、轻扫、自定义)

手势状态枚举如下:

复制代码 代码如下:

typedef ns_enum(nsinteger, uigesturerecognizerstate) {
  uigesturerecognizerstatepossible,  // 尚未识别是何种手势操作(但可能已经触发了触摸事件),默认状态
  uigesturerecognizerstatebegan,   // 手势已经开始,此时已经被识别,但是这个过程中可能发生变化,手势操作尚未完成
  uigesturerecognizerstatechanged,  // 手势状态发生转变
  uigesturerecognizerstateended,   // 手势识别操作完成(此时已经松开手指)
  uigesturerecognizerstatecancelled, // 手势被取消,恢复到默认状态
  uigesturerecognizerstatefailed,   // 手势识别失败,恢复到默认状态
  uigesturerecognizerstaterecognized = uigesturerecognizerstateended // 手势识别完成,同uigesturerecognizerstateended
};

对于离散型手势 uitapgesturerecgnizer 要么被识别,要么失败,点按(假设点按次数设置为1,并且没有添加长按手势)下去一次不松开则此时什么也不会发生,松开手指立即识别并调用操作事件,并且状态为3(已完成)。
但是连续型手势要复杂一些,就拿旋转手势来说,如果两个手指点下去不做任何操作,此时并不能识别手势(因为我们还没旋转)但是其实已经触发了触摸开始事件,此时处于状态0;如果此时旋转会被识别,也就会调用对应的操作事件,同时状态变成1(手势开始),但是状态1只有一瞬间;紧接着状态变为2(因为我们的旋转需要持续一会),并且重复调用操作事件(如果在事件中打印状态会重复打印2);松开手指,此时状态变为3,并调用1次操作事件。

3、使用手势的步骤
使用手势很简单,分为三步:

创建手势识别器对象实例。创建时,指定一个回调方法,当手势开始,改变、或结束时,执行回调方法。

设置手势识别器对象实例的相关属性(可选部分)

添加到需要识别的 view 中。每个手势只对应一个 view,当屏幕触摸在 view 的边界内时,如果手势和预定的一样,那就会执行回调方法。

ps:一个手势只能对应一个 view,但是一个 view 可以有多个手势。建议在真机上测试这些手势,模拟器操作不太方便,可能导致认为手势失效的情况。(模拟器测试捏合和旋转手势时,按住 option 键,再用触摸板或鼠标操作)

4、举例说明
功能描述:

附加到两个图片视图 uiimageview 的有『拖动』、『捏合』、『旋转』、『点按』;

而『轻扫』和『自定义手势 kmgesturerecognizer』附加在根视图 uiview 中。

拖动:进行当前图片视图位置移动

捏合:进行当前图片视图缩放

旋转:进行当前图片视图角度旋转

点按:双击恢复当前图片视图的缩放、角度旋转、不透明度

长按:设置当前图片视图的不透明度为0.7

轻扫:左右轻扫设置两个图片视图为居中,同时以垂直居中的特定偏移量定位

自定义手势:挠痒功能,左右扫动共3次或以上,设置两个图片视图为居中,同时以水平居中的特定偏移量定位

效果如下:

IOS手势操作(拖动、捏合、旋转、点按、长按、轻扫、自定义)

kmgesturerecognizer.h

 #import <uikit/uikit.h>
 
 typedef ns_enum(nsuinteger, direction) {
  directionunknown,
  directionleft,
  directionright
 };
 
 @interface kmgesturerecognizer : uigesturerecognizer
 @property (assign, nonatomic) nsuinteger ticklecount; //挠痒次数
 @property (assign, nonatomic) cgpoint currentticklestart; //当前挠痒开始坐标位置
 @property (assign, nonatomic) direction lastdirection; //最后一次挠痒方向
 
 @end
kmgesturerecognizer.m

 #import "kmgesturerecognizer.h"
 #import <uikit/uigesturerecognizersubclass.h>
 
 @implementation kmgesturerecognizer
 #define kminticklespacing 20.0
 #define kmaxticklecount 3
 
 - (void)reset {
  _ticklecount = 0;
  _currentticklestart = cgpointzero;
  _lastdirection = directionunknown;
  
  if (self.state == uigesturerecognizerstatepossible) {
   self.state = uigesturerecognizerstatefailed;
  }
 }
 
 - (void)touchesbegan:(nsset *)touches withevent:(uievent *)event {
  uitouch *touch = [touches anyobject];
  _currentticklestart = [touch locationinview:self.view]; //设置当前挠痒开始坐标位置
 }
 
 - (void)touchesmoved:(nsset *)touches withevent:(uievent *)event {
  //『当前挠痒开始坐标位置』和『移动后坐标位置』进行 x 轴值比较,得到是向左还是向右移动
  uitouch *touch = [touches anyobject];
  cgpoint tickleend = [touch locationinview:self.view];
  cgfloat ticklespacing = tickleend.x - _currentticklestart.x;
  direction currentdirection = ticklespacing < 0 ? directionleft : directionright;
  
  //移动的 x 轴间距值是否符合要求,足够大
  if (abs(ticklespacing) >= kminticklespacing) {
   //判断是否有三次不同方向的动作,如果有则手势结束,将执行回调方法
   if (_lastdirection == directionunknown ||
    (_lastdirection == directionleft && currentdirection == directionright) ||
    (_lastdirection == directionright && currentdirection == directionleft)) {
    _ticklecount++;
    _currentticklestart = tickleend;
    _lastdirection = currentdirection;
    
    if (_ticklecount >= kmaxticklecount && self.state == uigesturerecognizerstatepossible) {
     self.state = uigesturerecognizerstateended;
     //nslog(@"自定义手势成功,将执行回调方法");
    }
   }
  }
 }
 
 - (void)touchesended:(nsset *)touches withevent:(uievent *)event {
  [self reset];
 }
 
 - (void)touchescancelled:(nsset *)touches withevent:(uievent *)event {
  [self reset];
 }
 
 @end

viewcontroller.h
#import <uikit/uikit.h>
#import "kmgesturerecognizer.h"

@interface viewcontroller : uiviewcontroller
@property (strong, nonatomic) uiimageview *imgv;
@property (strong, nonatomic) uiimageview *imgv2;
@property (strong, nonatomic) kmgesturerecognizer *customgesturerecognizer;

@end
viewcontroller.m

 #import "viewcontroller.h"
 
 @interface viewcontroller ()
 - (void)handlepan:(uipangesturerecognizer *)recognizer;
 - (void)handlepinch:(uipinchgesturerecognizer *)recognizer;
 - (void)handlerotation:(uirotationgesturerecognizer *)recognizer;
 - (void)handletap:(uitapgesturerecognizer *)recognizer;
 - (void)handlelongpress:(uilongpressgesturerecognizer *)recognizer;
 - (void)handleswipe:(uiswipegesturerecognizer *)recognizer;
 - (void)handlecustomgesturerecognizer:(kmgesturerecognizer *)recognizer;
 
 - (void)bindpan:(uiimageview *)imgvcustom;
 - (void)bindpinch:(uiimageview *)imgvcustom;
 - (void)bindrotation:(uiimageview *)imgvcustom;
 - (void)bindtap:(uiimageview *)imgvcustom;
 - (void)bindlongpress:(uiimageview *)imgvcustom;
 - (void)bindswipe;
 - (void)bingcustomgesturerecognizer;
 - (void)layoutui;
 @end
 
 @implementation viewcontroller
 
 - (void)viewdidload {
  [super viewdidload];
  
  [self layoutui];
 }
 
 - (void)didreceivememorywarning {
  [super didreceivememorywarning];
  // dispose of any resources that can be recreated.
 }
 
 #pragma mark - 处理手势操作
 /**
 * 处理拖动手势
 *
 * @param recognizer 拖动手势识别器对象实例
 */
 - (void)handlepan:(uipangesturerecognizer *)recognizer {
  //视图前置操作
  [recognizer.view.superview bringsubviewtofront:recognizer.view];
  
  cgpoint center = recognizer.view.center;
  cgfloat cornerradius = recognizer.view.frame.size.width / 2;
  cgpoint translation = [recognizer translationinview:self.view];
  //nslog(@"%@", nsstringfromcgpoint(translation));
  recognizer.view.center = cgpointmake(center.x + translation.x, center.y + translation.y);
  [recognizer settranslation:cgpointzero inview:self.view];
  
  if (recognizer.state == uigesturerecognizerstateended) {
  //计算速度向量的长度,当他小于200时,滑行会很短
  cgpoint velocity = [recognizer velocityinview:self.view];
  cgfloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
  cgfloat slidemult = magnitude / 200;
  //nslog(@"magnitude: %f, slidemult: %f", magnitude, slidemult); //e.g. 397.973175, slidemult: 1.989866
  
  //基于速度和速度因素计算一个终点
  float slidefactor = 0.1 * slidemult;
  cgpoint finalpoint = cgpointmake(center.x + (velocity.x * slidefactor),
          center.y + (velocity.y * slidefactor));
  //限制最小[cornerradius]和最大边界值[self.view.bounds.size.width - cornerradius],以免拖动出屏幕界限
  finalpoint.x = min(max(finalpoint.x, cornerradius),
       self.view.bounds.size.width - cornerradius);
  finalpoint.y = min(max(finalpoint.y, cornerradius),
       self.view.bounds.size.height - cornerradius);
  
  //使用 uiview 动画使 view 滑行到终点
  [uiview animatewithduration:slidefactor*2
       delay:0
       options:uiviewanimationoptioncurveeaseout
      animations:^{
       recognizer.view.center = finalpoint;
      }
      completion:nil];
 }
}

/**
* 处理捏合手势
*
* @param recognizer 捏合手势识别器对象实例
*/
- (void)handlepinch:(uipinchgesturerecognizer *)recognizer {
 cgfloat scale = recognizer.scale;
 recognizer.view.transform = cgaffinetransformscale(recognizer.view.transform, scale, scale); //在已缩放大小基础下进行累加变化;区别于:使用 cgaffinetransformmakescale 方法就是在原大小基础下进行变化
 recognizer.scale = 1.0;
}

/**
* 处理旋转手势
*
* @param recognizer 旋转手势识别器对象实例
*/
- (void)handlerotation:(uirotationgesturerecognizer *)recognizer {
 recognizer.view.transform = cgaffinetransformrotate(recognizer.view.transform, recognizer.rotation);
 recognizer.rotation = 0.0;
 }
 
 /**
 * 处理点按手势
 *
 * @param recognizer 点按手势识别器对象实例
 */
 - (void)handletap:(uitapgesturerecognizer *)recognizer {
  uiview *view = recognizer.view;
  view.transform = cgaffinetransformmakescale(1.0, 1.0);
  view.transform = cgaffinetransformmakerotation(0.0);
  view.alpha = 1.0;
 }
 
 /**
 * 处理长按手势
 *
 * @param recognizer 点按手势识别器对象实例
 */
 - (void)handlelongpress:(uilongpressgesturerecognizer *)recognizer {
  //长按的时候,设置不透明度为0.7
  recognizer.view.alpha = 0.7;
 }
 
 /**
 * 处理轻扫手势
 *
 * @param recognizer 轻扫手势识别器对象实例
 */
 - (void)handleswipe:(uiswipegesturerecognizer *)recognizer {
  //代码块方式封装操作方法
  void (^positionoperation)() = ^() {
   cgpoint newpoint = recognizer.view.center;
   newpoint.y -= 20.0;
   _imgv.center = newpoint;
   
   newpoint.y += 40.0;
   _imgv2.center = newpoint;
  };
  
  //根据轻扫方向,进行不同控制
  switch (recognizer.direction) {
   case uiswipegesturerecognizerdirectionright: {
    positionoperation();
    break;
   }
   case uiswipegesturerecognizerdirectionleft: {
    positionoperation();
    break;
   }
   case uiswipegesturerecognizerdirectionup: {
    break;
   }
   case uiswipegesturerecognizerdirectiondown: {
    break;
   }
  }
 }
 
 /**
 * 处理自定义手势
 *
 * @param recognizer 自定义手势识别器对象实例
 */
 - (void)handlecustomgesturerecognizer:(kmgesturerecognizer *)recognizer {
  //代码块方式封装操作方法
  void (^positionoperation)() = ^() {
   cgpoint newpoint = recognizer.view.center;
   newpoint.x -= 20.0;
   _imgv.center = newpoint;
   
   newpoint.x += 40.0;
   _imgv2.center = newpoint;
  };
  
  positionoperation();
 }
 
 
 #pragma mark - 绑定手势操作
 /**
 * 绑定拖动手势
 *
 * @param imgvcustom 绑定到图片视图对象实例
 */
 - (void)bindpan:(uiimageview *)imgvcustom {
  uipangesturerecognizer *recognizer = [[uipangesturerecognizer alloc] initwithtarget:self
                     action:@selector(handlepan:)];
  [imgvcustom addgesturerecognizer:recognizer];
 }
 
 /**
 * 绑定捏合手势
 *
 * @param imgvcustom 绑定到图片视图对象实例
 */
 - (void)bindpinch:(uiimageview *)imgvcustom {
  uipinchgesturerecognizer *recognizer = [[uipinchgesturerecognizer alloc] initwithtarget:self
                      action:@selector(handlepinch:)];
  [imgvcustom addgesturerecognizer:recognizer];
  //[recognizer requiregesturerecognizertofail:imgvcustom.gesturerecognizers.firstobject];
 }
 
 /**
 * 绑定旋转手势
 *
 * @param imgvcustom 绑定到图片视图对象实例
 */
 - (void)bindrotation:(uiimageview *)imgvcustom {
  uirotationgesturerecognizer *recognizer = [[uirotationgesturerecognizer alloc] initwithtarget:self
                       action:@selector(handlerotation:)];
  [imgvcustom addgesturerecognizer:recognizer];
 }
 
 /**
 * 绑定点按手势
 *
 * @param imgvcustom 绑定到图片视图对象实例
 */
 - (void)bindtap:(uiimageview *)imgvcustom {
  uitapgesturerecognizer *recognizer = [[uitapgesturerecognizer alloc] initwithtarget:self
                     action:@selector(handletap:)];
  //使用一根手指双击时,才触发点按手势识别器
  recognizer.numberoftapsrequired = 2;
  recognizer.numberoftouchesrequired = 1;
  [imgvcustom addgesturerecognizer:recognizer];
 }
 
 /**
 * 绑定长按手势
 *
 * @param imgvcustom 绑定到图片视图对象实例
 */
 - (void)bindlongpress:(uiimageview *)imgvcustom {
  uilongpressgesturerecognizer *recognizer = [[uilongpressgesturerecognizer alloc] initwithtarget:self action:@selector(handlelongpress:)];
  recognizer.minimumpressduration = 0.5; //设置最小长按时间;默认为0.5秒
  [imgvcustom addgesturerecognizer:recognizer];
 }
 
 /**
 * 绑定轻扫手势;支持四个方向的轻扫,但是不同的方向要分别定义轻扫手势
 */
 - (void)bindswipe {
  //向右轻扫手势
  uiswipegesturerecognizer *recognizer = [[uiswipegesturerecognizer alloc] initwithtarget:self
                      action:@selector(handleswipe:)];
  recognizer.direction = uiswipegesturerecognizerdirectionright; //设置轻扫方向;默认是 uiswipegesturerecognizerdirectionright,即向右轻扫
  [self.view addgesturerecognizer:recognizer];
  [recognizer requiregesturerecognizertofail:_customgesturerecognizer]; //设置以自定义挠痒手势优先识别
  
  //向左轻扫手势
  recognizer = [[uiswipegesturerecognizer alloc] initwithtarget:self
               action:@selector(handleswipe:)];
  recognizer.direction = uiswipegesturerecognizerdirectionleft;
  [self.view addgesturerecognizer:recognizer];
  [recognizer requiregesturerecognizertofail:_customgesturerecognizer]; //设置以自定义挠痒手势优先识别
 }
 
 /**
 * 绑定自定义挠痒手势;判断是否有三次不同方向的动作,如果有则手势结束,将执行回调方法
 */
 - (void)bingcustomgesturerecognizer {
  //当 recognizer.state 为 uigesturerecognizerstateended 时,才执行回调方法 handlecustomgesturerecognizer:
  
  //_customgesturerecognizer = [kmgesturerecognizer new];
  _customgesturerecognizer = [[kmgesturerecognizer alloc] initwithtarget:self
                  action:@selector(handlecustomgesturerecognizer:)];
  [self.view addgesturerecognizer:_customgesturerecognizer];
 }
 
 - (void)layoutui {
  //图片视图 _imgv
  uiimage *img = [uiimage imagenamed:@"emoticon_tusiji_icon"];
  cgfloat cornerradius = img.size.width;
  _imgv = [[uiimageview alloc] initwithimage:img];
  _imgv.frame = cgrectmake(20.0, 20.0,
        cornerradius * 2, cornerradius * 2);
  _imgv.userinteractionenabled = yes;
  _imgv.layer.maskstobounds = yes;
  _imgv.layer.cornerradius = cornerradius;
  _imgv.layer.borderwidth = 2.0;
  _imgv.layer.bordercolor = [uicolor graycolor].cgcolor;
  [self.view addsubview:_imgv];
  
  //图片视图 _imgv2
  img = [uiimage imagenamed:@"emoticon_tusiji_icon2"];
  cornerradius = img.size.width;
  _imgv2 = [[uiimageview alloc] initwithimage:img];
  _imgv2.frame = cgrectmake(20.0, 40.0 + _imgv.frame.size.height,
        cornerradius * 2, cornerradius * 2);
  _imgv2.userinteractionenabled = yes;
  _imgv2.layer.maskstobounds = yes;
  _imgv2.layer.cornerradius = cornerradius;
  _imgv2.layer.borderwidth = 2.0;
  _imgv2.layer.bordercolor = [uicolor orangecolor].cgcolor;
  [self.view addsubview:_imgv2];
  
  
  [self bindpan:_imgv];
  [self bindpinch:_imgv];
  [self bindrotation:_imgv];
  [self bindtap:_imgv];
  [self bindlongpress:_imgv];
  
  [self bindpan:_imgv2];
  [self bindpinch:_imgv2];
  [self bindrotation:_imgv2];
  [self bindtap:_imgv2];
  [self bindlongpress:_imgv2];
  
  //为了处理手势识别优先级的问题,这里需先绑定自定义挠痒手势
  [self bingcustomgesturerecognizer];
  [self bindswipe];
 }
 
 @end

以上代码就是关于ios手势操作(拖动、捏合、旋转、点按、长按、轻扫、自定义)的详解,希望对大家有所帮助。