iOS Controls UIResponder class

stay iOS in UIResponder Class is designed to respond to user actions and handle various events , We know UIApplication、UIView、UIViewController These classes are directly inherited from UIResponder,UIWindow It is directly inherited from UIView A special View, So these classes can respond to events . Of course, our custom inheritance is from UIView Of View And custom inheritance from UIViewController All controllers can respond to events .iOS These objects that can respond to events are usually called responders .
iOS Middle event Event It can be divided into two kinds , One is system events ( If you call 、 Memory warning, etc ), In addition, we call it non system events ( Touch event 、 Sports Events 、 Remote control events ).
Whether it's system events or non system events ,iOS Systems are the first to know about events , Then add the event to the currently running app Of UIApplication In the event queue .UIApplication Events are pulled from the event queue in first in first out order , And then distribute it for response .
 
UIApplication The received system events are distributed to its agents AppDelegate Object to process , Other non system events are passed to UIApplication Of keyWindow To find the right view To respond .
 
This paper focuses on non system events , Including touch events (Touch Events)、 Sports Events (Motion Events)、 Remote control events (Remote Control Events, Such as the event triggered by inserting headphones to adjust the volume ). Refer to this article for system events http://www.cnblogs.com/shaoting/p/5029092.html
 
 
Now let's base on UIResponder.h Header file to describe all aspects of responding to events .

In this part, we mainly introduce 3 Types of events , Touch event , Sports Events , Remote control events . When a user triggers an event ,UIKit Will create a UIEvent Event object ( About iOS The event object can refer to This article ), The event object is added to a FIFO In the FIFO queue ,UIApplication Object to handle events , An event object is taken from the queue head for distribution .

1. Touch event

@interface UIResponder : NSObject
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;// Touch the screen
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;// Move on the screen
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;// Leave the screen
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;// System events interfere with

this 4 One method is the most primitive handling of touch events 4 A way , They represent the touch screen , Move on the screen , Leaving the screen and being disturbed by high priority events in the system ( Like a phone call ) Cancel the touch event . in addition UIKit The framework provides us with... For touch events UIGestureRecognizer Gesture recognition class , Basically meeting most of our needs ( You can refer to This article ). Here is the bottom-level processing method , For example, it can be used to implement the drawing type APP.
above-mentioned UIApplication Object takes the event object out of the queue for distribution , For touch events ,UIApplication I'm going to give it to keyWindow,Window Will hand over the incident to UIGestureRecognizer Handle , If UIGestureRecognizer Identified the events passed through , Then give it to the corresponding target To deal with ( About iOS Gesture events can refer to This article ), Events are no longer delivered , If UIGestureRecognizer It doesn't recognize the events that come through ( Maybe there is no view to add gestures , Maybe gesture recognition is not successful ), Events are passed to the view tree , It is divided into two steps: finding the receiver and responding to the event .
1. stay iOS Find the final receiver in the view tree , That is to say, touch the top layer of the event View On , This process is called hit-testing( Test hit ), Finding the final hit view through layer by layer traversal is called hit-test view.
UIView There are two ways to determine hit-test view.

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;

 
 

This is a picture of me from apple Screenshots from official documents , All that's shown here View It's all loaded into the main window On , Suppose we touch the screen ViewD Region , When we don't have overload UIView Of hitTest:withEvent: and pointInside:withEvent: These two methods , The default processing of the system is as follows :

  • keyWindow call pointInside:withEvent: Determine if the touch point is in its frame Within the scope of , return Yes, Traverse keyWindow Of subView->ViewA.
  • ViewA call pointInside:withEvent: Determine if the touch point is in its frame Within the scope of , return Yes, Traverse ViewA Of subView->ViewB、ViewC( About ViewB and ViewC Which one to execute first , It's based on ViewA Order of adding child controls , Always execute before add subView. What if ViewB Add ViewC)
  • ViewC call pointInside:withEvent: Determine if the touch point is in its frame Within the scope of , return Yes, Traverse ViewC Of subView->ViewD、ViewE
  • ViewE call pointInside:withEvent: Determine if the touch point is in its frame Within the scope of , return NO,ViewE Of hitTest:withEvent: return nil( If it is executed first ViewB The situation of , hypothesis ViewB There are also child nodes subView, because ViewB Of pointInside:withEvent: return NO,ViewB Of hitTest:withEvent:` Go straight back to nil Is not going to traverse ViewB Of the child nodes of )
  • ViewD call pointInside:withEvent: Determine if the touch point is in its frame Within the scope of , return Yes And there are no child nodes subView,ViewD Of hitTest:withEvent: return ViewD In itself , That is the final hit-test view( No more traversal ViewB)iewB

    It should be noted that :View.isHidden=YES View.alpha<=0.01 View.userInterfaceEnable=NO View.enable = NO( To inherit from UIControl Of View) the 4 Under different circumstances ,View Of pointInside return NO,hitTest Method returns nil
    Default UIImageView Of userInterfaceEnable=NO

2. eureka hit-test view, The next step is to respond to events . Explain , For touch events , No matter what View Whether to deal with the incident , Even if it's application adopt [application beginIgnoringInteractionEvents] Ignoring touch events , above hit-testing It's still going on , It only affects the process of the second step event response . Next we will introduce iOS Responder chain (Responder chain)

 
This is a screenshot of the responder chain I took from the official document . Let's take a look at the picture on the left : Tagged as ① The steps are where you want to go 1 Found hit-test view It responds to this event as the first responder , If it's time to view Not by rewriting or encapsulating touch A series of methods to handle the event , Default touch The implementation of is to call the parent class touch Method , Pass on the event . Here by 1-> Passed to its parent class 2,2 It's the root of the controller view,-> Pass on to vc controller -> Pass it to the window window-> Pass on to application

Let's look at the picture on the right : Tagged as ① The steps are where you want to go 1 Found hit-test view, And it's the root of the controller view And there's the parent view , Events are passed to the controller -> And then pass it on to the father -> To the controller , And then pass it to the parent view window ->application. In fact, the left part of the figure above can also be understood as that the window is the parent view of the controller root view . If the whole responder chain ends , They didn't deal with the incident , Then the event will be discarded .

To sum up, the transmission process of the responder chain is : By the first responder ( For touch events, it's hist-test view) Start to pass up . If the view is the root view of the controller , Pass it to the controller first , Pass it to the parent view , If it's not the root view of the controller , Pass it directly to the parent view .
Just call the method of the parent class in the responder's processing method , You can have multiple views and controllers respond to the same event , The fundamental purpose of the responder chain is : Shared events , Let multiple views and controllers handle the same event differently .

2. Sports Events

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event NS_AVAILABLE_IOS(3_0);
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event NS_AVAILABLE_IOS(3_0);
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event NS_AVAILABLE_IOS(3_0);

this 3 The first method is the most primitive handling of motion events 3 A way , The sports events dealt with here refer in particular to shake event , The shaking of the phone triggers the acceleration sensor inside the phone , Can be used to achieve a shake to calculate the number of motion steps and other applications . Similar to touch events , this 3 Each method represents the beginning of the event 、 End of event and cancellation of event due to system interference .
Accelerometer accelerometer It's actually made up of three accelerometers , To measure separately X,Y and Z The change of the speed of the straight path of the axis . Combined with all three accelerometers, it can detect the movement of the device in any direction and obtain the current direction of the device . about shake In terms of events , We don't care 3 Motion in two directions , Only as an event object . If it's just the general direction of processing equipment , You don't need to know the direction vector , Such as horizontal screen vertical screen rotation , We can use UIDevice class ( Reference article ). If we need to know 3 The movement in two directions should be dealt with more carefully , As mentioned above, the number of floors and other types of sports APP, Accelerometers can be accessed using the core motion frame , Gyroscope and equipment movement class to do processing (Core Motion Reference article )
The responder chain described above is for shake Events also apply , It's just , No, hit-testing The process , If the currently displayed view interface does not have one view Declare as the first responder ( call becomeFirstResponder Declare and View Need to rewrite canBecomeFirstResponder Method returns YES, The default return is NO), By default, the current view controller is the first responder , And pass events along the responder chain , Until it's dealt with . If there is a view declared as the first responder , The event is passed from this view until it is processed , If the event is not handled in the end and UIApplication Of applicationSupportsShakeToEdit The attribute is YES( The default is YES), When the keyboard is displayed , The system will have a warning whether to undo the input . Wechat and QQ The effect of shaking the mobile phone to prompt the user to cancel the input . For more information on undo NSUndoManager

3. Remote control events ( This article will not discuss it for the time being )

4.UI Control can't respond to events

Be careful :UIView.enable = NO; And can't respond to events !

Most of the above is transferred from http://www.jianshu.com/p/2dda99a0e09a

 
 

iOS Controls UIResponder Class

  1. Swift - Generate factory classes for various controls ( Include label , Button , Input box, etc )

    stay iOS In development , Sometimes a lot of controls are used in the page , If you want to create one by one and then set the style, it is very troublesome . We can create a factory class that generates various controls , In this way, it can be called when necessary . Take a custom factory class as an example , Its ...

  2. To design a iOS Control

    Reprinted from :http://blog.csdn.net/zhangao0086/article/details/45622875 The level of code : Compiling . Can run . Testable . Can be read . Maintainable . Reusable Preface A control from the outside ...

  3. fight to win or die Windows 10 (34) - Control ( Progress class ): RangeBase, Slider, ProgressBar, ProgressRing

    [ Source download ] fight to win or die Windows 10 (34) - Control ( Progress class ): RangeBase, Slider, ProgressBar, ProgressRing author :webabcd Introduce backwater ...

  4. fight to win or die Windows 10 (33) - Control ( Select class ): ListBox, RadioButton, CheckBox, ToggleSwitch

    [ Source download ] fight to win or die Windows 10 (33) - Control ( Select class ): ListBox, RadioButton, CheckBox, ToggleSwitch author :webabcd Introduce backwater ...

  5. fight to win or die Windows 10 (32) - Control ( Select class ): Selector, ComboBox

    [ Source download ] fight to win or die Windows 10 (32) - Control ( Select class ): Selector, ComboBox author :webabcd Introduce the battle behind the back Windows 10 And Control ( Select class ) Sel ...

  6. fight to win or die Windows 10 (31) - Control ( Button class ): ButtonBase, Button, HyperlinkButton, RepeatButton, ToggleButton, AppBarButton, AppBarToggleButton

    [ Source download ] fight to win or die Windows 10 (31) - Control ( Button class ): ButtonBase, Button, HyperlinkButton, RepeatButton, ToggleButt ...

  7. fight to win or die Windows 10 (30) - Control ( The text class ): AutoSuggestBox

    [ Source download ] fight to win or die Windows 10 (30) - Control ( The text class ): AutoSuggestBox author :webabcd Introduce the battle behind the back Windows 10 And Control ( The text class ) AutoSug ...

  8. fight to win or die Windows 10 (29) - Control ( The text class ): RichTextBlock, RichTextBlockOverflow, RichEditBox

    [ Source download ] fight to win or die Windows 10 (29) - Control ( The text class ): RichTextBlock, RichTextBlockOverflow, RichEditBox author :webabcd ...

  9. fight to win or die Windows 10 (28) - Control ( The text class ): TextBox, PasswordBox

    [ Source download ] fight to win or die Windows 10 (28) - Control ( The text class ): TextBox, PasswordBox author :webabcd Introduce the battle behind the back Windows 10 And Control ( The text class ) T ...

Random recommendation

  1. LinqToXml ( One ) Create Xml file By Dom /Linq

    at present , stay xml A popular development model in the field of application programming is W3C Provided DOM( Document object model ), stay .net Framework Through namespace System.Xml Support for this technology . With Linq to XMl ...

  2. Wechat development summary -PHP

    The function point : 1.  Web page authorization to obtain wechat user information Users visit third-party Web pages in wechat clients , The official account can be authorized by WeChat web page. , To get basic user information , To realize business logic . Be careful :Scope by snsapi_base Only get ...

  3. C++ The template of learning notes (1)—— From function overloading to function templates

    One . function overloading Because function overloading is easier to understand , And it's very helpful for us to understand the meaning of function template , So let's start with a classic example to show why we use function overloading , It's much more effective than reading text definitions . Now let's write one to exchange two int Variable value ...

  4. Intellij Idea establish Web Project introduction ( One )

    Related software : Intellij Idea14:http://pan.baidu.com/s/1nu16VyD JDK7:http://pan.baidu.com/s/1dEstJ5f Tomcat(ap ...

  5. xmpp Extensible message of protocol (messaging) And state (presence) The core of the agreement : RFC 3920

    attach :asmack It's no longer needed ,4.1 After the smack Already available in android It has been used. . XMPP Clients:   http://xmpp.org/software/clients.html An ...

  6. [ turn ]mysql Start and view the log of

    mysql There are several kinds of logs : Error log :  -log-err Query log :  -log Slow query log : -log-slow-queries Update log :    -log-update Binary log :-log-bin journal ...

  7. tomcat The configuration file server.xml Detailed explanation Reprint http://blog.csdn.net/yuanxuegui2008/article/details/6056754

    Element name attribute explain server port Specify a port , This port is responsible for listening and closing tomcat  Request shutdown Specifies the command string to send to the port service name Appoint service  Name ...

  8. About css Some summary of floating

    Let's give floating a definition first Floating can be understood as making a certain div Element out of standard flow , Floating on standard flow , Not at the same level as standard flow . From the test The floating relationship between elements is determined by the previous element. If the previous element is floating, it will follow the floating element ...

  9. crontab Linux Timer tool

    To use crontab Timer tool , You have to start cron service : service cron start crontab The grammar of , In case of emergency in the future . First, let's give Zhang Chao a diagram of awesome power : crontab Description of each parameter : -e : The executive editor ...

  10. C++ The difference between declaration and definition of variable

    The difference between variable declaration and definition We're in programming , The definition and declaration of variables are used all the time , But sometimes we are not very clear about this concept , Know how it works , But I don't know what happened , Now I will briefly introduce their differences as follows :( Look at my advice ...