Event Handling in iOS

Source: Internet
Author: User

Introduction: Event Handling in iOS is a very important and difficult place. Related to the response chain of the local side of the question, many of the two or three years of old birds may not be able to answer a very professional. Here's a detailed description of event handling in iOS and the responder chain.

1. Three major events
    1. Touch events
    2. Speeding up the timekeeping room
    3. Remote control Events
2. Responder Object
    • Not all objects in iOS can handle events, only inherited UIResponder objects can receive and handle events. We call it响应者对象
    • UIApplication, Uiviewcontroller, and UIView inherit from Uiresponder, so they are both responder objects that can receive and handle events
2.1 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;
2.2 UIView Touch Event handling
    • UIView is a subclass of Uiresponder that can handle different touch events with the following 4 methods
Root or multiple 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 move on the view, the system automatically calls the following method of view (which continues to be called as the finger moves)-(void)Touchesmoved:(nsset *)Touches withevent:(uievent *)event//one or more fingers out of view, the system will automatically call the following method of view-(void)Touchesended:(nsset *)Touches withevent:(uievent *)event//a system event before the touch ends(for example, phone call-in)Will interrupt the touch process, the system will automatically invoke the following method of view-(void)Touchescancelled:(nsset *)Touches withevent:(uievent *)Event

Tip: Uitouch objects are stored in the touches

2.3 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

the role of Uitouch
-Keep information related to your fingers, such as 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

      提示:iPhone开发中,要避免使用双击事件

Properties of the Uitouch

//The window where the touch was generated@property(nonatomic,ReadOnly, retain)UIWindow*window;//The view at which the touch was generated@property(nonatomic,ReadOnly, retain)UIView*view;//Tap the number of times in a short time, you can judge by Tapcount click, double click or more click@property(nonatomic,ReadOnly) Nsuinteger Tapcount;//Record the time when the touch event was generated or changed, in seconds, with very little@property(nonatomic,ReadOnly)NstimeintervalTimestamp//Status of the current touch event@property(nonatomic,ReadOnly) Uitouchphase phase;

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
2.4 uievent
    • Each occurrence of an event produces a Uievent object

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

Common Properties
1. Event Type
@property(nonatomic,readonly) UIEventType type;
@property(nonatomic,readonly) UIEventSubtype subtype;

2. Time the event was generated
@property(nonatomic,readonly) NSTimeInterval timestamp;

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

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 :-(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.

3. Generation and delivery of events 3.1 rules for event passing
    1. When a touch event occurs, the system adds the event to a UIApplication managed 事件队列
    2. UIApplication will take the first event out of the event queue and distribute the event for processing, typically sending the event to the application's主窗口(keyWindow)
    3. The main window will find one in the view hierarchy 最合适的视图 to handle touch events, which is the first step in the entire event processing process.
    4. 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 ...
3.2 Event Delivery Example

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 to find the most appropriate control to handle the event:

      1. Determine if you can receive touch events

        UIView three cases of not receiving touch events

        • Do not receive user interaction:userinteractionenabled = no
        • Hidden:hidden = YES
        • Transparent:alpha = 0.0 ~ 0.01
      2. Determine if the touch points are on their own
      3. Iterate through the child controls backwards, repeating the previous two steps
      4. If there are no child controls that meet the criteria, then you are best suited to handle

提示:UIImageView的userInteractionEnabled默认就是NO,因此UIImageView以及它的子控件默认是不能接收触摸事件的

4. Detailed process of response chain 4.1 touch event handling
    1. 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

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

    3. 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

4.2 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
4.3 The complete process of event delivery
    1. First pass the event object from top to bottom (passed by the parent control to the child control), and find the most appropriate control to handle the event.

    2. Call 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. The last responder's touches is then called .... method

      How to determine the previous 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 view of the controller, then the parent control is the last responder
4.4 Event Delivery process for responder chains
    1. 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
    2. 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
    3. If the window object is not processed, it passes the event or message to the UIApplication object
    4. If UIApplication cannot process the event or message, it is discarded
5. Example explanation

Implement one of the following cases:
The yellow view is above the button and the transparency of the view is 0.5, which now requires the response button when clicked on the view and on the button

    1. New project, layout the interface on storyboard, customize Yellowview file, link to yellow view

    2. Customize a Iboutlet UIButton in Yellowview and drag the line from the variable
      to storyboard.

    3. Code implementation Logic

#import "YellowView.h"  @interface yellowview ()@property(nonatomic,Weak)Iboutlet UIButton*BTN;@end @implementation yellowview //used to test whether UIView has been clicked- (void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{NSLog(@'%s ', __func__);} - (UIView*) HitTest: (Cgpoint) Point withevent: (Uievent *) event{//Convert the current view coordinate to a button    CgpointBTNP = [ SelfConvertpoint:point TOVIEW:_BTN];//Judging the current point is not in the button, if the button is on the Back button    if([_btn POINTINSIDE:BTNP withevent:event]) {return_BTN; }Else{return[SuperHittest:point Withevent:event]; }}@end

Test Results:
1. Click inside the yellow view, outside the button, to print

2. Click on the button, the title color of the button changes, indicating that button responded to the

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Event Handling in iOS

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.