iOS Development--ui Advanced (12) event handling, touch events, uitouch,uievent, responder chain, gesture recognition

Source: Internet
Author: User

Touch events
A variety of events occur during the user's use of the app

One, the event in iOS can be divided into 3 major types

Touch events
Accelerometer Events
Remote control Events

Responder Object
Not all objects in iOS can handle events, only objects that inherit Uiresponder can receive and handle events. We call it "responder object."

UIApplication, Uiviewcontroller, and UIView inherit from Uiresponder, so they are both responder objects that can receive and handle events


Second, Uiresponder

Uiresponder internally provides the following methods to handle events
Touch events
-(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;

Accelerometer Events
-(void) Motionbegan: (uieventsubtype) Motion withevent: (uievent *) event;
-(void) motionended: (uieventsubtype) Motion withevent: (uievent *) event;
-(void) motioncancelled: (uieventsubtype) Motion withevent: (uievent *) event;

Remote control Events
-(void) Remotecontrolreceivedwithevent: (Uievent *) event;


Three, UIView touch event processing

UIView is a subclass of Uiresponder that can handle different touch events with the following 4 methods
One or more fingers start to touch the view, the system will automatically call the following method of view
-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) event

One or more fingers moving on the view, the system automatically calls the view's following method (which continues to be called as the finger moves)
-(void) touchesmoved: (Nsset *) touches withevent: (Uievent *) event

One or more fingers to leave the view, the system will automatically call the following method of view
-(void) touchesended: (Nsset *) touches withevent: (Uievent *) event

A system event, such as a phone call, interrupts the touch process before the touch is finished, and the system automatically calls the following method of view
-(void) touchescancelled: (Nsset *) touches withevent: (Uievent *) event
Tip: Uitouch objects are stored in the touches


Iv. Uitouch

When the user touches the screen with one finger, a Uitouch object associated with the finger is created

One finger corresponds to a Uitouch object

1, the role of Uitouch
Holds information about the finger, such as the location, time, and stage of the touch

When the finger moves, the system updates the same Uitouch object so that it can keep the finger in the touch position

When the finger leaves the screen, the system destroys the corresponding Uitouch object

Tip: To avoid using double-click events in iphone development!

2. Properties of Uitouch
The window where the touch is generated
@property (Nonatomic,readonly,retain) UIWindow *window;

The view at which the touch was generated
@property (Nonatomic,readonly,retain) UIView *view;

The number of times you tap the screen in a short time can be judged by Tapcount click, double tap or more
@property (nonatomic,readonly) Nsuinteger Tapcount;

Records the time when a touch event is generated or changed, in seconds
@property (nonatomic,readonly) nstimeinterval timestamp;

The state of the current touch event
@property (nonatomic,readonly) uitouchphase phase;

3. Methods of Uitouch
-(Cgpoint) Locationinview: (UIView *) view;
The return value indicates the position of the touch on the view
The position returned here is for the view's coordinate system (in the upper left corner of the view is the origin (0, 0))
When called, the view parameter is nil, which returns the position of the touch point in the UIWindow.

-(Cgpoint) Previouslocationinview: (UIView *) view;
This method records the position of the previous touch point


Wu, Uievent

Each occurrence of an event produces a Uievent object

Uievent: Called an event object to record the time and type of event generation

2. Common Properties

Event Type
@property (nonatomic,readonly) uieventtype type;
@property (nonatomic,readonly) Uieventsubtype subtype;

Time the event was generated
@property (nonatomic,readonly) nstimeinterval timestamp;

Uievent also provides a way to get a touch object on a view (Uitouch)

3. Touches and Event parameters
A complete touch process that goes through 3 states:
Touch Start:-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) event
Touch move:-(void) touchesmoved: (Nsset *) touches withevent: (Uievent *) event
Touch End:-(void) touchesended: (Nsset *) touches withevent: (Uievent *) event
Touch Cancel (May experience):-(void) touchescancelled: (Nsset *) touches withevent: (Uievent *) event

4 Touch Event handling methods, all with Nsset *touches and uievent *event two parameters
Once a complete touch process, only one event object is generated, and 4 touch methods are the same as the same event parameter

If two fingers touch a view at the same time, view will only call once Touchesbegan:withevent: method, touches parameter is loaded with 2 Uitouch objects

If these two fingers touch the same view one after the other, then view will call 2 times Touchesbegan:withevent: Method, and only one Uitouch object is included in the touches parameter of each call

Depending on the number of Uitouch in the touches, you can tell whether it's a single touch or multi-touch.


Vi. generation and transmission of events

1. After a touch event, the system will add the event to an event queue managed by UIApplication

UIApplication takes the first event from the event queue and distributes the event for processing, typically sending an event to the application's main window (Keywindow)

The main window will find the most appropriate view in the view hierarchy to handle touch events, which is the first step in the entire event processing process.

Once the appropriate view control is found, the touches method of the view control is called to do the specific event handling
Touchesbegan ...
Touchesmoved ...
Touchedended ...

2. Example of event delivery


Touch event delivery is passed from parent control to child control
Click on the Green View:
UIApplication, UIWindow, white-green
Click on the Blue View:
UIApplication, UIWindow, white-orange blue
Click on the Yellow view:
UIApplication, UIWindow, White, orange and blue

If the parent control cannot receive touch events, then the child control cannot receive touch events (Master)

How do I find the most appropriate control to handle an event?
1) can I receive touch events?
2) is the touch point on its own?
3) Iterate through the array of child controls, repeating the previous two steps
4) If there are no child controls that meet the criteria, then you are best suited to handle
HitTest method Internal principle (simulated apple)

//when to call: Whenever an event is passed to a control, it is called//role: Find the most suitable view for you//uiapplication, [UIWindow hittest:withevent:] Find the most appropriate view telling system//Point: points that the current finger touches//point: Points on the method caller's coordinate system-(UIView *) HitTest: (cgpoint) point withevent: (Uievent *)Event{//UIView *fitview = [Super Hittest:point withevent:event]; //1. Determine if the window can receive events    if(self.userinteractionenabled = = NO | | self.hidden = = YES | | Self.alpha <=0.01)returnNil; //2. Judging the next point is not on the window//not on the window    if([Self pointinside:point withevent:Event] = = NO)returnNil; //3. Traversing a child control array from backward to forward    intCount = (int) Self.subviews.count; //0 1     for(inti = count-1; I >=0; i--) {        //Get child controlsUIView *childview =Self.subviews[i]; //conversion of a coordinate system to convert a point on a window to a point on a child control//Convert a point on your control to a point on which controlCgpoint CHILDP =[self convertpoint:point toview:childview]; UIView*fitview = [Childview hittest:childp withevent:Event]; if(Fitview) {//If we can find the most suitable view            returnFitview; }    }    //4. There is no more suitable view than yourself    returnSelf ;}

3, UIView do not receive three cases of touch events
1. Do not receive user interaction
userinteractionenabled = NO

2. Hide
Hidden = YES

3. Transparent
Alpha = 0.0 ~ 0.01

Tip: Uiimageview's userinteractionenabled default is no, so Uiimageview and its child controls cannot receive touch events by default.


Seven, the responder chain

1. Detailed process of touch event processing
A touch event that occurs after a user taps the screen and, after a series of passes, finds the most appropriate view control to handle the event

Once the most appropriate view control is found, the touches method of the control is called to make specific event handling
Touchesbegan ...
Touchesmoved ...
Touchedended ...

The default practice of these touches methods is to pass the event up the responder chain, handing the event to the previous responder for processing

2, the responder chain


Responder chain: A chain linked by multiple responder objects
Role: can clearly see the relationship between each responder, and can let an event multiple object processing.
Responder object: An object that can handle events

3. The complete process of event delivery
1> first passes the event object from top to bottom (passed by the parent control to the child control), and finds the most appropriate control to handle the event.

2> calls the touches of the most appropriate control .... method

3> if [super touches ...] is called, the event is passed up the responder chain to the previous responder

4> then calls the last responder's touches .... method

4. How to judge the last responder
1> If the current view is a view of the controller, then the controller is the last responder

2> If the current view is not the controller's view, then the parent control is the last responder

5. The event delivery process of the responder chain
If the view controller is present, it is passed to the controller, and if the controller does not exist, it is passed to its parent view
In the top-most view of the view hierarchy, if you cannot process the received event or message, it passes the event or message to the Window object for processing
If the window object is not processed, it passes the event or message to the UIApplication object
If UIApplication cannot process the event or message, it is discarded

Eight, gesture recognition

1, the practice of listening to touch events
If you want to listen to a touch event on a view, the previous practice is to
Customizing a View
Implement the touches method of view, implement the specific processing code inside the method

There are a few obvious drawbacks to monitoring the view touch event through the touches method
You have to customize the view
Because the touch event is monitored in the touches method inside the view, it is not possible to allow other external objects to listen to the touch events of the view by default
Not easily differentiate user's specific gesture behavior

After IOS 3.2, Apple introduced the gesture recognition feature (Gesture recognizer), which greatly simplifies developer development in touch event handling

2, Uigesturerecognizer
In order to complete gesture recognition, the gesture recognizer must be used----Uigesturerecognizer

With Uigesturerecognizer, you can easily identify some common gestures that users make on a view

Uigesturerecognizer is an abstract class that defines the basic behavior of all gestures and uses its subclasses to handle specific gestures
UITapGestureRecognizer (percussion)
Uipinchgesturerecognizer (pinch, for zooming)
Uipangesturerecognizer (drag)
Uiswipegesturerecognizer (Swipe)
Uirotationgesturerecognizer (swivel)
Uilongpressgesturerecognizer (Long Press)


2.1, UITapGestureRecognizer (tap gesture)
Each gesture recognizer uses a similar set of steps, such as UITapGestureRecognizer:

To create a gesture recognizer object
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];

To set the specific properties of a gesture Recognizer object
2 consecutive strokes
tap.numberoftapsrequired = 2;
It takes 2 fingers to tap together.
tap.numberoftouchesrequired = 2;

Add a gesture recognizer to the corresponding view
[Self.iconview Addgesturerecognizer:tap];

Triggering of a listening gesture
[Tap addtarget:self Action: @selector (Tapiconview:)];


2.2. Uilongpressgesturerecognizer (Long press gesture)

- (void) setuplongpress{//long-Press gesturesUilongpressgesturerecognizer *longpress =[[Uilongpressgesturerecognizer alloc] initwithtarget:self action: @selector (longpress:)]; [_imageview addgesturerecognizer:longpress];}//When to call: Long Press when the call, and as long as the finger does not leave, the drag will always be called, when the finger is lifted will also call- (void) Longpress: (Uilongpressgesturerecognizer *) longpress{//Note: In future development, long-press gestures generally need to be judged    if(Longpress.state = =uigesturerecognizerstateended) {NSLog (@"%s", __func__); }}

2.3. Uiswipegesturerecognizer (swipe)

- (void) setupswipe{//a gesture can only correspond to One Direction//set the direction of the swipe to the right (default to right if not set)Uiswipegesturerecognizer *swiper =[[Uiswipegesturerecognizer alloc] initwithtarget:self action: @selector (swipe:)]; //set the direction of the swipeSwiper.direction =Uiswipegesturerecognizerdirectionright;                [_imageview Addgesturerecognizer:swiper]; //set the direction of the swipe to go leftUiswipegesturerecognizer *swipe =[[Uiswipegesturerecognizer alloc] initwithtarget:self action: @selector (swipe:)]; //set the direction of the swipeSwipe.direction =Uiswipegesturerecognizerdirectionleft; [_imageview addgesturerecognizer:swipe];}- (void) Swipe: (Uiswipegesturerecognizer *) swipe{if(Swipe.direction = =uiswipegesturerecognizerdirectionright) {        //Swipe right}Else{        //Swipe leftNSLog (@"%s left", __func__); }}

3. Status of Gesture recognition

typedef ns_enum (Nsinteger, uigesturerecognizerstate) {//No touch event occurs, default state of all gesture recognitionuigesturerecognizerstatepossible,//when a gesture has started but has not changed or completedUigesturerecognizerstatebegan,//Gesture State Changeuigesturerecognizerstatechanged,//Gesture Completionuigesturerecognizerstateended,//gesture cancellation, revert to possible stateuigesturerecognizerstatecancelled,//gesture failed to revert to possible stateuigesturerecognizerstatefailed,//recognition to gesture recognitionuigesturerecognizerstaterecognized =uigesturerecognizerstateended};

iOS Development--ui Advanced (12) event handling, touch events, uitouch,uievent, responder chain, gesture recognition

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.