iOS 경 점,터치,제스처 코드 개발

18764 단어 iOS살살터치손짓
1.응답 자 체인
UIResponsder 를 초 클래스 로 하 는 모든 종 류 는 응답 자 입 니 다.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
{

}

2.검 측 스 캔 이벤트
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
3.다 지 경 소 를 실현 한다.

//
// 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
4.여러 번 가볍게 검사

//
// 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
5.반죽 과 회전 검사

#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

6.사용자 정의 제스처

//
// 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

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기