IOS touch events and gestures

Source: Internet
Author: User

13.1 event Overview

13.2 touch events

13.3 gestures

13.1 event Overview

An event is the object that the system continuously sends to the application when the user's fingers touch the screen and move on the screen.

The system passes an event to an object that can be processed according to a specific path.

In iOS, A uitouch object represents a touch, and a uievent object represents an event. The event object contains all the touch objects corresponding to the current multi-point touch sequence. It also provides a touch object associated with a specific view or window.

Recipient

The responder object is an object that can respond to an event and process it.

Uiresponder is the base class of all responder objects. It not only processes events, but also defines programming interfaces for common responder behaviors.

Uiapplication, uiview, and all the uikit classes (including uiwindows) derived from uiview are directly or indirectly inherited from the uiresponder class.

The first responder is the responder object (usually a uiview object) in the application that is currently responsible for receiving touch events ). The uiwindow object sends an event to the first responder in the form of a message, giving it the opportunity to process the event first. If the first responder does not process the event, the system sends the event (via message) to the next responder in the responder chain to see if it can process the event.

Responder chain

A response chain is the connection sequence of a responder object. event or action messages (or menu editing messages) are transmitted in sequence. It allows the respondent to forward the event handling responsibilities to other higher-level objects. The application finds the appropriate processing object by passing an event up. Because the click detection view is also a response object, applications can also use the response chain when handling touch events. The response chain is composed of a series of next responders.

Handling principles of the responder chain

1. Click "detection View" or "First responder" to send an event or action message to its view controller (if any). If no View Controller exists, it is passed to its parent view.

2. If a view or its view controller cannot process this event or action message, it will be passed to the parent view of the view.

3. In this view level, each subsequent parent view follows the above pattern if it cannot process this event or action message.

4. If the top-level view cannot process this event or action message, it is passed to the uiwindow object for processing.

5. If the uiwindow object cannot be processed, it is passed to the single-piece application object uiapplication.

If the application object cannot process this event or action message, it will be discarded.

13.2 touch events

The Touch Information has two aspects: Time and Space. The time information is called a phase (phrase), which indicates whether the touch is in the starting, moving, or static state, and when it ends-that is, when your fingers are lifted from the screen. The Touch information also includes the location information of the current view or window, and the previous location information (if any ). When a finger contacts the screen, the touch is associated with a window or view, which is maintained throughout the lifecycle of the event.

Touch event stage

Event handling method

In a given touch phase, if a new touch action or an existing touch action changes, the application will send these messages:

When one or more fingers touch the screen, send the touchesbegan: withevent: Message.

When one or more fingers move on the screen, send the touchesmoved: withevent: Message.

When one or more fingers exit the screen, send the touchesended: withevent: Message.

When the touch sequence is canceled by system events such as incoming calls, a touchescancelled: withevent: message is sent.

Touch event instance eventinfo

#import <UIKit/UIKit.h>@interface TouchView : UIView {}- (void)logTouchInfo:(UITouch *)touch;@end

 

@implementation TouchView- (void)logTouchInfo:(UITouch *)touch {    CGPoint locInSelf = [touch locationInView:self];    CGPoint locInWin = [touch locationInView:nil];    NSLog(@"    touch.locationInView = {%2.3f, %2.3f}", locInSelf.x, locInSelf.y);    NSLog(@"    touch.locationInWin = {%2.3f, %2.3f}", locInWin.x, locInWin.y);    NSLog(@"    touch.phase = %d", touch.phase);    NSLog(@"    touch.tapCount = %d", touch.tapCount);}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {    NSLog(@"touchesBegan - touch count = %d", [touches count]);    for(UITouch *touch in event.allTouches) {        [self logTouchInfo:touch];    }}

 

Touch. phase: the stage of touch events.

Touch. tapcount, the number of touch events, you can determine the double-click event.

The alltouches method of uievent can obtain a set of touch points and determine multi-touch events.

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {    NSLog(@"touchesMoved - touch count = %d", [touches count]);    for(UITouch *touch in event.allTouches) {        [self logTouchInfo:touch];    }}- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {    NSLog(@"touchesEnded - touch count = %d", [touches count]);    for(UITouch *touch in event.allTouches) {        [self logTouchInfo:touch];    }}- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {    NSLog(@"touchesCancelled - touch count = %d", [touches count]);    for(UITouch *touch in event.allTouches) {        [self logTouchInfo:touch];    }}

 

13.3 gestures

Gestures are very important in the iPhone. gestures are the way your hands touch the screen.

Single click

Double hitting

Multi-touch (close and expand)

Light stroke

... ...

Single-click and double-click instances: multitap

Red and blue

#import <UIKit/UIKit.h>@interface MultiTapView : UIView {}@end

 

#import "MultiTapView.h"@implementation MultiTapView- (void)turnBlue {  self.backgroundColor = [UIColor blueColor];}- (void)turnRed {  self.backgroundColor = [UIColor redColor];}//START:code.MultiTapView.touchesBegan:- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {  UITouch *touch = [touches anyObject];  if(touch.tapCount == 2) {      [[self class] cancelPreviousPerformRequestsWithTarget:self                                                  selector:@selector(turnRed)                                                    object:nil];  }}//END:code.MultiTapView.touchesBegan://START:code.MultiTapView.touchesEnded:- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {  UITouch *touch = [touches anyObject];  if(touch.tapCount == 1) {      [self performSelector:@selector(turnRed) withObject:nil afterDelay:0.10f];  }  if(touch.tapCount == 2) {      [self turnBlue];  }}//END:code.MultiTapView.touchesEnded:@end

[Self defined mselector: @ selector (turnred) withobject: Nil afterdelay: 0.10f]; The turnred method is called after 0.1 seconds.

[[Self class] cancelpreviousperformrequestswithtarget: Self selector: @ selector (turnred) object: Nil]; cancels the call method turnred.

Multi-touch (close and expand) pinchzoom

Pinchzoomview. h file

#import <UIKit/UIKit.h>#import <QuartzCore/QuartzCore.h>@interface PinchZoomView : UIView {    CALayer *robotLayer;    CGFloat previousDistance;    CGFloat zoomFactor;    BOOL pinchZoom;}@property(nonatomic, retain) CALayer *robotLayer;@end

 

M file

#import "PinchZoomView.h"@implementation PinchZoomView@synthesize robotLayer;- (void)awakeFromNib {    self.robotLayer = [CALayer layer];    UIImage *image = [UIImage imageNamed:@"Robot.png"];    self.robotLayer.contents = (id)[image CGImage];    self.robotLayer.bounds = CGRectMake(0.0f, 0.0f, image.size.width, image.size.height);    self.robotLayer.position = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));    [self.layer addSublayer:self.robotLayer];    pinchZoom = NO;    previousDistance = 0.0f;    zoomFactor = 1.0f;}

 

Awakefromnib when the NIB file is loaded, the loader sends an awakefromnib message to every object in the NIB file. Each object can define its own awakefromnib method to respond to this message, perform some necessary operations. That is to say, awakefromnib is executed to create a view object through the NIB file.

Robotlayer is a calayer object. In this example, we add an image object to the robotlayer object. To use calayer, You need to introduce the header file <quartzcore/quartzcore. h> and add the quartzcore. Framework framework.

//START:code.PinchZoomView.touchesBegan- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {    if(event.allTouches.count == 2) {        pinchZoom = YES;        NSArray *touches = [event.allTouches allObjects];        CGPoint pointOne = [[touches objectAtIndex:0] locationInView:self];        CGPoint pointTwo = [[touches objectAtIndex:1] locationInView:self];        previousDistance = sqrt(pow(pointOne.x - pointTwo.x, 2.0f) +                                 pow(pointOne.y - pointTwo.y, 2.0f));    } else {        pinchZoom = NO;    }}//END:code.PinchZoomView.touchesBegan

 

Previusdistance is used to obtain the distance between two points.

Pow is a square function.

SQRT is the square root function.

//START:code.PinchZoomView.touchesMoved- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {    if(YES == pinchZoom && event.allTouches.count == 2) {        NSArray *touches = [event.allTouches allObjects];        CGPoint pointOne = [[touches objectAtIndex:0] locationInView:self];        CGPoint pointTwo = [[touches objectAtIndex:1] locationInView:self];        CGFloat distance = sqrt(pow(pointOne.x - pointTwo.x, 2.0f) +                                 pow(pointOne.y - pointTwo.y, 2.0f));        zoomFactor += (distance - previousDistance) / previousDistance;        zoomFactor = fabs(zoomFactor);         previousDistance = distance;        self.robotLayer.transform = CATransform3DMakeScale(zoomFactor, zoomFactor, 1.0f);    }}//END:code.PinchZoomView.touchesMoved

 

//START:code.PinchZoomView.touchesEnded- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {    if(event.allTouches.count != 2) {        pinchZoom = NO;        previousDistance = 0.0f;    }    if(event.allTouches.count == 1) {//        NSArray *touches = [event.allTouches allObjects];//        UITouch *touch = [touches objectAtIndex:0];        UITouch *touch = [touches anyObject];        NSInteger tapCount = [touch tapCount];        if (tapCount == 2) {            zoomFactor += 0.4;            self.robotLayer.transform = CATransform3DMakeScale(zoomFactor, zoomFactor, 1.0f);        } else if (tapCount == 3) {            zoomFactor += 0.6;            self.robotLayer.transform = CATransform3DMakeScale(zoomFactor, zoomFactor, 1.0f);        } else if (tapCount == 4) {            zoomFactor += 0.8;            self.robotLayer.transform = CATransform3DMakeScale(zoomFactor, zoomFactor, 1.0f);        }    }}//END:code.PinchZoomView.touchesEnded- (void)dealloc {    self.robotLayer = nil;    [robotLayer release];    [super dealloc];}

 

Note:
1. This tutorial is based on instructor Guan Dongsheng.
2 Based on black apple 10.6.8 and xcode4.2
3. I am a beginner. What are you looking?
4. The tutorial will be updated continuously as I learn
5. I copied the document from the word notes. Sorry for the format.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.