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

iOS轻点、触摸和手势代码开发

程序员文章站 2023-12-20 13:51:28
一、响应者链 以uiresponder作为超类的任何类都是响应者。uiview和uicontrol是uireponder的子类,因此所有视图和所有控件都是响应者。 1、...

一、响应者链

以uiresponder作为超类的任何类都是响应者。uiview和uicontrol是uireponder的子类,因此所有视图和所有控件都是响应者。

1、初始相应器
事件首先会传递给uiapplication对象,接下来会传递给应用程序的uiwindow,uiwindow会选择一个初始相应器来处理事件。初始响应器会选择下面的方式选择1、对于触摸事件,uiwindow会确定用户触摸的视图,然后将事件交给注册了这个视图的手势识别器或则注册视图层级更高的手势识别器。只要存在能处理事件的识别器,就不会再继续找了。如果没有的话,被触摸视图就是初始相应器,事件也会传递给它。

2、对于用户摇晃设备产生的或者是来自远程遥控设备事件,将会传递给第一响应器
如果初始响应器不处理时间,它会将事件传递给它的父视图(如果存在的话),或者传递给视图控制器(如果此视图是视图控制器的视图)。如果视图控制器不处理事件,它将沿着响应器链的层级继续传给父视图控制器(如果存在的话)。
如果在整个视图层级中都没与能处理事件的视图或控制器,事件就会被传递给应用程序的窗口。如果窗口不能处理事件,而应用委托是uiresponder的子类,uiapplication对象就会将其传递给应用程序委托。最后,如果应用委托不是uiresponder的子类,或者不处理这个事件,那么这个事件将会被丢弃。

4个手势通知方法

#pragma mark - touch event methods
// 用户第一次触摸屏幕时被调用
- (void)touchesbegan:(nsset<uitouch *> *)touches withevent:(uievent *)event
{

}

// 当发生某些事件(如来电呼叫)导致手势中断时被调用
- (void)touchescancelled:(nsset<uitouch *> *)touches withevent:(uievent *)event
{

}

// 当用户手指离开屏幕时被调用
- (void)touchesended:(nsset<uitouch *> *)touches withevent:(uievent *)event
{

}

// 当用户手指移动时触发
- (void)touchesmoved:(nsset<uitouch *> *)touches withevent:(uievent *)event
{

}

二、检测扫描事件

1、手动检测

//
// viewcontroller.m
// swipes
//
// created by jierism on 16/8/4.
// copyright © 2016年 jierism. all rights reserved.
//

#import "viewcontroller.h"
// 设置检测范围
static cgfloat const kminimmgesturelength = 25;
static cgfloat const kmaximmvariance = 5;

@interface viewcontroller ()
@property (weak, nonatomic) iboutlet uilabel *label;
@property (nonatomic) cgpoint gesturestartpoint;
@end

@implementation viewcontroller


- (void)viewdidload {
  [super viewdidload];
  // do any additional setup after loading the view, typically from a nib.
}

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

- (void)touchesbegan:(nsset<uitouch *> *)touches withevent:(uievent *)event
{
  uitouch *touch = [touches anyobject];
  self.gesturestartpoint = [touch locationinview:self.view];
}

- (void)touchesmoved:(nsset<uitouch *> *)touches withevent:(uievent *)event
{
  uitouch *touch = [touches anyobject];
  cgpoint currentposition = [touch locationinview:self.view];
  // 返回一个float的绝对值
  cgfloat deltax = fabsf(self.gesturestartpoint.x - currentposition.x);
  cgfloat deltay = fabsf(self.gesturestartpoint.y - currentposition.y);
  
  // 获得两个增量后,判断用户在两个方向上移动过的距离,检测用户是否在一个方向上移动得足够远但在另一个方向移动得不够来形成轻扫动作
  if (deltax >= kminimmgesturelength && deltay <= kmaximmvariance) {
    self.label.text = @"horizontal swipe detected";
    // 2s后擦除文本
    dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(2 * nsec_per_sec)),
            dispatch_get_main_queue(),
            ^{
      self.label.text = @"";
    });
  }else if (deltay >= kminimmgesturelength && deltax <= kmaximmvariance){
    self.label.text = @"vertical swipe detected";
    dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(2 * nsec_per_sec)), dispatch_get_main_queue(), ^{
      self.label.text = @"";
    });
  }
}

@end

2、识别器检测

//
// viewcontroller.m
// swipes
//
// created by jierism on 16/8/4.
// copyright © 2016年 jierism. all rights reserved.
//

#import "viewcontroller.h"


@interface viewcontroller ()
@property (weak, nonatomic) iboutlet uilabel *label;
@property (nonatomic) cgpoint gesturestartpoint;
@end

@implementation viewcontroller


- (void)viewdidload {
  [super viewdidload];
  // do any additional setup after loading the view, typically from a nib.
  //创建两个手势识别器
  // 1、水平方向识别器
  uiswipegesturerecognizer *horizontal = [[uiswipegesturerecognizer alloc] initwithtarget:self action:@selector(reporthorizontalswipe:)];

  horizontal.direction = uiswipegesturerecognizerdirectionleft | uiswipegesturerecognizerdirectionright;
  [self.view addgesturerecognizer:horizontal];
  
  // 2、垂直方向识别器
  uiswipegesturerecognizer *vertical = [[uiswipegesturerecognizer alloc] initwithtarget:self action:@selector(reportverticalswipe:)];
  vertical.direction = uiswipegesturerecognizerdirectionup | uiswipegesturerecognizerdirectiondown;
  [self.view addgesturerecognizer:vertical];
}

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

- (void)reporthorizontalswipe:(uigesturerecognizer *)recognizer
{

  self.label.text = @"horizontal swipe detected";
  // 2s后擦除文本
  dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(2 * nsec_per_sec)),
          dispatch_get_main_queue(),
          ^{
            self.label.text = @"";
          });
}

- (void)reportverticalswipe:(uigesturerecognizer *)recognizer
{
  self.label.text = @"vertical swipe detected";
  // 2s后擦除文本
  dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(2 * nsec_per_sec)),
          dispatch_get_main_queue(),
          ^{
            self.label.text = @"";
          });
}

@end

三、实现多指轻扫

//
// viewcontroller.m
// swipes
//
// created by jierism on 16/8/4.
// copyright © 2016年 jierism. all rights reserved.
//

#import "viewcontroller.h"



@interface viewcontroller ()
@property (weak, nonatomic) iboutlet uilabel *label;
@property (nonatomic) cgpoint gesturestartpoint;
@end

@implementation viewcontroller


- (void)viewdidload {
  [super viewdidload];
  // do any additional setup after loading the view, typically from a nib.
  
  for (nsuinteger touchcount = 1; touchcount <= 5; touchcount++) {
    //创建两个手势识别器
    // 1、水平方向识别器
    uiswipegesturerecognizer *horizontal = [[uiswipegesturerecognizer alloc] initwithtarget:self action:@selector(reporthorizontalswipe:)];
    
    horizontal.direction = uiswipegesturerecognizerdirectionleft | uiswipegesturerecognizerdirectionright;
    [self.view addgesturerecognizer:horizontal];
    
    // 2、垂直方向识别器
    uiswipegesturerecognizer *vertical = [[uiswipegesturerecognizer alloc] initwithtarget:self action:@selector(reportverticalswipe:)];
    vertical.direction = uiswipegesturerecognizerdirectionup | uiswipegesturerecognizerdirectiondown;
    [self.view addgesturerecognizer:vertical];
  }
  
}

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

- (nsstring *)descriptionfortouchcount:(nsuinteger)touchcount
{
  switch (touchcount) {
    case 1:
      return @"single";
    case 2:
      return @"double";
    case 3:
      return @"triple";
    case 4:
      return @"quadruple";
    case 5:
      return @"quintuple";
      
    default:
      return @"";
  }
}

- (void)reporthorizontalswipe:(uigesturerecognizer *)recognizer
{

  self.label.text = [nsstring stringwithformat:@"%@ horizontal swipe detected",[self descriptionfortouchcount:[recognizer numberoftouches]]];
  // 2s后擦除文本
  dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(2 * nsec_per_sec)),
          dispatch_get_main_queue(),
          ^{
            self.label.text = @"";
          });
}

- (void)reportverticalswipe:(uigesturerecognizer *)recognizer
{
  self.label.text = [nsstring stringwithformat:@"%@ vertical swipe detected",[self descriptionfortouchcount:[recognizer numberoftouches]]];
  // 2s后擦除文本
  dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(2 * nsec_per_sec)),
          dispatch_get_main_queue(),
          ^{
            self.label.text = @"";
          });
}

@end

四、检测多次轻点

//
// viewcontroller.m
// taptaps
//
// created by jierism on 16/8/4.
// copyright © 2016年 jierism. all rights reserved.
//

#import "viewcontroller.h"

@interface viewcontroller ()
@property (weak, nonatomic) iboutlet uilabel *singlelabel;
@property (weak, nonatomic) iboutlet uilabel *doublelabel;
@property (weak, nonatomic) iboutlet uilabel *triplelabel;
@property (weak, nonatomic) iboutlet uilabel *quadruplelabel;

@end

@implementation viewcontroller

- (void)viewdidload {
  [super viewdidload];
  // do any additional setup after loading the view, typically from a nib.
  // 创建4个点击手势识别器
  uitapgesturerecognizer *singletap = [[uitapgesturerecognizer alloc] initwithtarget:self action:@selector(singletap)];
  singletap.numberoftapsrequired = 1;
  singletap.numberoftouchesrequired = 1;
  // 附加到视图
  [self.view addgesturerecognizer:singletap];
  
  uitapgesturerecognizer *doubletap = [[uitapgesturerecognizer alloc] initwithtarget:self action:@selector(doubletap)];
  doubletap.numberoftapsrequired = 2;
  doubletap.numberoftouchesrequired = 1;
  [self.view addgesturerecognizer:doubletap];
  // 当doubletap响应“失败”才运行singletap
  [singletap requiregesturerecognizertofail:doubletap];
  
  uitapgesturerecognizer *tripletap = [[uitapgesturerecognizer alloc] initwithtarget:self action:@selector(tripletap)];
  tripletap.numberoftapsrequired = 3;
  tripletap.numberoftouchesrequired = 1;
  [self.view addgesturerecognizer:tripletap];
  [doubletap requiregesturerecognizertofail:tripletap];
  
  uitapgesturerecognizer *quadrupletap = [[uitapgesturerecognizer alloc] initwithtarget:self action:@selector(quadrupletap)];
  quadrupletap.numberoftapsrequired = 4;
  quadrupletap.numberoftouchesrequired = 1;
  [self.view addgesturerecognizer:quadrupletap];
  [tripletap requiregesturerecognizertofail:quadrupletap];
}

- (void)singletap
{
  self.singlelabel.text = @"single tap detected";
  dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(2 * nsec_per_sec)), dispatch_get_main_queue(), ^{
    self.singlelabel.text = @"";
  });
}

- (void)doubletap
{
  self.doublelabel.text = @"double tap detected";
  dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(2 * nsec_per_sec)), dispatch_get_main_queue(), ^{
    self.doublelabel.text = @"";
  });
}

- (void)tripletap
{
  self.triplelabel.text = @"triple tap detected";
  dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(2 * nsec_per_sec)), dispatch_get_main_queue(), ^{
    self.triplelabel.text = @"";
  });
}

- (void)quadrupletap
{
  self.quadruplelabel.text = @"quadruple tap detected";
  dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(2 * nsec_per_sec)), dispatch_get_main_queue(), ^{
    self.quadruplelabel.text = @"";
  });
}


@end

五、检测捏合和旋转

#import <uikit/uikit.h>

@interface viewcontroller : uiviewcontroller<uigesturerecognizerdelegate>


@end

//
// viewcontroller.m
// pinchme
//
// created by jierism on 16/8/4.
// copyright © 2016年 jierism. all rights reserved.
//

#import "viewcontroller.h"

@interface viewcontroller ()

@property (strong,nonatomic) uiimageview *imageview;

@end

@implementation viewcontroller

// 当前缩放比例,先前缩放比例
cgfloat scale,previousscale;
// 当前旋转角度,先前旋转角度
cgfloat rotation,previousrotation;

- (void)viewdidload {
  [super viewdidload];
  // do any additional setup after loading the view, typically from a nib.
  previousscale = 1;
  
  uiimage *image = [uiimage imagenamed:@"yosemite-meadows"];
  self.imageview = [[uiimageview alloc] initwithimage:image];
  // 对图像启用交互功能
  self.imageview.userinteractionenabled = yes;
  self.imageview.center = self.view.center;
  [self.view addsubview:self.imageview];
  
  // 建立捏合手势识别器
  uipinchgesturerecognizer *pinchgesture = [[uipinchgesturerecognizer alloc] initwithtarget:self action:@selector(dopinch:)];
  pinchgesture.delegate = self;
  [self.imageview addgesturerecognizer:pinchgesture];
  
  // 建立旋转手势识别器
  uirotationgesturerecognizer *rotationgesture = [[uirotationgesturerecognizer alloc] initwithtarget:self action:@selector(dororate:)];
  rotationgesture.delegate = self;
  [self.imageview addgesturerecognizer:rotationgesture];
}


- (bool)gesturerecognizer:(uigesturerecognizer *)gesturerecognizer shouldrecognizesimultaneouslywithgesturerecognizer:(uigesturerecognizer *)othergesturerecognizer
{
  // 允许捏合手势和旋转手势同时工作。否则,先开始的手势识别器会屏蔽另一个
  return yes;
}

// 根据手势识别器中获得的缩放比例和旋转角度对图像进行变换
- (void)transformimageview
{
  cgaffinetransform t = cgaffinetransformmakescale(scale * previousscale, scale * previousscale);
  t = cgaffinetransformrotate(t, rotation + previousrotation);
  self.imageview.transform = t;
}

- (void)dopinch:(uipinchgesturerecognizer *)gesture
{
  scale = gesture.scale;
  [self transformimageview];
  if (gesture.state == uigesturerecognizerstateended) {
    previousscale = scale * previousscale;
    scale = 1;
  }
}


- (void)dororate:(uirotationgesturerecognizer *)gesture
{
  rotation = gesture.rotation;
  [self transformimageview];
  if (gesture.state == uigesturerecognizerstateended) {
    previousrotation = rotation + previousrotation;
    rotation = 0;
  }
}


@end

六、自定义手势

//
// checkmarkrecognizer.m
// checkplease
//
// created by jierism on 16/8/4.
// copyright © 2016年 jierism. all rights reserved.
//

#import "checkmarkrecognizer.h"
#import "cgpointutils.h"
#import <uikit/uigesturerecognizersubclass.h> // 一个重要目的是使手势识别器的state属性可写,子类将使用这个机制断言我们所观察的手势已成功完成

// 设置检测范围
static cgfloat const kminimuncheckmarkangle = 80;
static cgfloat const kmaximumcheckmarkangle = 100;
static cgfloat const kminimumcheckmarklength = 10;

@implementation checkmarkrecognizer{
  // 前两个实例变量提供之前的线段
  cgpoint lastpreviouspoint;
  cgpoint lastcurrentpoint;
  // 画出的线段长度
  cgfloat linelengthsofar;
}


// 用lastpreviouspoint和lastcurrentpoint组成第一条线段,跟第二条线段形成角度去完成手势
- (void)touchesbegan:(nsset<uitouch *> *)touches withevent:(uievent *)event
{
  [super touchesbegan:touches withevent:event];
  uitouch *touch = [touches anyobject];
  cgpoint point = [touch locationinview:self.view];
  lastpreviouspoint = point;
  lastcurrentpoint = point;
  linelengthsofar = 0.0;
}

- (void)touchesmoved:(nsset<uitouch *> *)touches withevent:(uievent *)event
{
  [super touchesmoved:touches withevent:event];
  uitouch *touch = [touches anyobject];
  cgpoint previouspoint = [touch previouslocationinview:self.view];
  cgpoint currentpoint = [touch locationinview:self.view];
  cgfloat angle = anglebetweenlines(lastpreviouspoint, lastcurrentpoint, previouspoint, currentpoint);
  if (angle >= kminimuncheckmarkangle && angle <= kmaximumcheckmarkangle && linelengthsofar > kminimumcheckmarklength) {
    self.state = uigesturerecognizerstaterecognized;
  }
  linelengthsofar += distancebetweenpoints(previouspoint, currentpoint);
  lastpreviouspoint = previouspoint;
  lastcurrentpoint = currentpoint;
}

@end
//
// viewcontroller.m
// checkplease
//
// created by jierism on 16/8/4.
// copyright © 2016年 jierism. all rights reserved.
//

#import "viewcontroller.h"
#import "checkmarkrecognizer.h"

@interface viewcontroller ()

@property (weak, nonatomic) iboutlet uiimageview *imageview;


@end

@implementation viewcontroller

- (void)viewdidload {
  [super viewdidload];
  // do any additional setup after loading the view, typically from a nib.
  checkmarkrecognizer *check = [[checkmarkrecognizer alloc] initwithtarget:self action:@selector(docheck:)];
  [self.view addgesturerecognizer:check];
  self.imageview.hidden = yes;
}

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

- (void)docheck:(checkmarkrecognizer *)check
{
  self.imageview.hidden = no;
  dispatch_after(dispatch_time(dispatch_time_now, (int64_t)(2 * nsec_per_sec)), dispatch_get_main_queue(), ^{
    self.imageview.hidden = yes;
  });
}


@end

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: