Event handling Guide for ios--events driver

Source: Internet
Author: User
Tags uikit

An event is an object that is sent to an application to notify the user of its action. In iOS, events can take many forms: multi-touch events, motion (, move, gesture) events---for example, the device's accelerometer (accelerometer)-and events that control multimedia. (The last type of event is called a remote control event because it starts with a headset or other external access accessory). As shown in the following:


In iOS, the Uikit and core motion frameworks are responsible for event propagation and delivery.


I. Type of event and delivery:
An iphone, ipad, or ipod touch device has several ways to integrate input stream data into your application's access. Multi-touch technology directly operates views, including virtual keyboards. Accelerometer in three directions. GPs and direction. These devices process the underlying data that is transmitted to the system framework when touch, device movement, and location changes are detected. The framework packages the data and delivers them to the application as an event to handle.

1,uikit Event object and type:
Many events are instances of uievent in the Uikit framework. Uievent objects may encapsulate the associated state of an event, such as an associated touch. It also records the time that the event was generated.
Currently, Uikit can identify 3 types of events: Touch events, "shaking" (shaking) motion events, and Remote-control events. The Uievent class declares an enum (enum) constant:

typedef enum {
Uieventtypetouches,
Uieventtypemotion,
Uieventtyperemotecontrol,
} Uieventtype;


typedef enum {
Uieventsubtypenone = 0,
Uieventsubtypemotionshake = 1,
Uieventsubtyperemotecontrolplay = 100,
Uieventsubtyperemotecontrolpause = 101,
Uieventsubtyperemotecontrolstop = 102,
Uieventsubtyperemotecontroltoggleplaypause = 103,
Uieventsubtyperemotecontrolnexttrack = 104,
Uieventsubtyperemotecontrolprevioustrack = 105,
Uieventsubtyperemotecontrolbeginseekingbackward = 106,
Uieventsubtyperemotecontrolendseekingbackward = 107,
Uieventsubtyperemotecontrolbeginseekingforward = 108,
Uieventsubtyperemotecontrolendseekingforward = 109,
} uieventsubtype
;

each event has an event type and subtype, with the type and subtype properties to getsubtype of touch eventsAlwaysUieventsubtypenone.
You should never retain a Uievent object. If you need to preserve the current state of the event object, you should copy and store these states in the appropriate way, such as storing these values in a dictionary.
Devices running iOS can send other types of events, which are not uievent objects, but still encapsulate some hardware information.

2, Event Delivery:
When the user touches the device, iOS recognizes the set of touches and packs it into a Uievent object and puts it into the event queue of the active application. If the system considers the device's shake to be a motion event, an object representing the event is also placed in the application's event queue. A singleton UIApplication object extracts an event from the top of the queue and distributes it for processing. In general, it sends events to the focus window of the app's critical window--user event.

3, Responder object and responder chain:


Two, multi-touch events:
1, event and touch: A Type property of Uieventtypetouches Uievent object represents a touch event. When the finger touches the screen and moves on its surface, the system continuously sends these touch event objects into an application. The event provides a snapshot of all touches.

2, Touch event delivery:
1) By default, a view receives a touch event if you set itsuserinteractionenabled property is no, it turns off posting of touch events。 A view cannot receive touch events when it is hidden or transparent.
2) an app can calluiapplication beginignoringinteractionevents and then calls the Endignoringinteractionevents method
3) By default, a view in a multi-touch sequence identifies only one finger of the touch event. If youwant the view to handle multiple touches, you must set the Mutipletouchenabled property to Yes
4) By default, a view of theExclusivetouchproperty is no, which means that this view does not block other view receive touches. If you set this property to Yes, if you are tracking touch, then only this view can track the touch. Other view cannot receive these touch messages. However, this view also does not receive touch information associated with other views.
5) UIView subclasses can overload hittest:withevent: to restrict the posting of multi-touch events to their child views.

3, handle multi-touch events:
Must be a subclass of Uiresponder, which can be: UIView, Uiviewcontroller, Uiimageview, uiapplication, or UIWindow. Methods for handling 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

Each Uitouch object has a touch stage, for example, Touchesbegan: Association Uitouchphasebegan, which you can obtain by Uitouch the phase property of the object.

4. Basic handling of touch events:
An arbitrary touch message is obtained by nsset the Anyobject message of the object.
An important method of UitouchLocationinview:。 A set of corresponding methods:Previouslocationinview:
TapcountGets the number of taps.
Alltouches gets all the touch information because all touch information for a touch event is not necessarily in a view, so the first parameter of the touch Nsset should be the touch information associated with that view. As shown in the following:

  can send uievent to Touchesforwindow objects: messages, Touchesforview : Message.

5, handle the tap gesture: if you want to handle the click Gesture and double-click gesture, you can handle the double-click in your touch event as follows:
-(void) touchesended: (Nsset *) touches withevent: (uievent *) Event {
    for (Uitouch *touch in touches) {
        if ( Touch.tapcount >= 2) {
            [Self.superview Bringsubviewtofront:self];
       }
   }
}
And then add a click gesture recognition.
or:
1) Execute performSelector:withObject:afterDelay after touch: This selector represents the action to be performed by the click Gesture.
2) At the beginning of the next touch, check if Tapcount is 2, and if so, Cancelpreviousperformrequestswithtarget: method. If not, identify the click event. As follows:

-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) event {
    Uitouch *atouch = [touches anyobject];
    if (Atouch.tapcount = = 2) {
[NSObject cancelpreviousperformrequestswithtarget:self];
}

}

-(void) touchesmoved: (Nsset *) touches withevent: (Uievent *) Event {
}

-(void) touchesended: (Nsset *) touches withevent: (Uievent *) Event {
Uitouch *thetouch = [touches anyobject];
if (Thetouch.tapcount = = 1) {
Nsdictionary *touchloc = [Nsdictionary dictionarywithobject:
[Nsvalue Valuewithcgpoint:[thetouch locationinview:self]] forkey:@ "Location";
[Self performselector: @selector (handlesingletap:) Withobject:touchloc afterdelay:0.3];
} else if (Thetouch.tapcount = = 2) {
Double-tap:increase image size by 10% "
CGRect myframe = self.frame;
MyFrame.size.width + = Self.frame.size.width * 0.1;
MyFrame.size.height + = Self.frame.size.height * 0.1;
Myframe.origin.x-= (self.frame.origin.x * 0.1)/2.0;
MYFRAME.ORIGIN.Y-= (SELF.FRAME.ORIGIN.Y * 0.1)/2.0;
[UIView Beginanimations:nil Context:null];
[Self setframe:myframe];
[UIView commitanimations];
}

}

-(void) Handlesingletap: (Nsdictionary *) touches {
Single-tap:decrease image size by 10% "
CGRect myframe = self.frame;
MyFrame.size.width-= Self.frame.size.width * 0.1;
MyFrame.size.height-= Self.frame.size.height * 0.1;
Myframe.origin.x + = (self.frame.origin.x * 0.1)/2.0;
MYFRAME.ORIGIN.Y + = (SELF.FRAME.ORIGIN.Y * 0.1)/2.0;
[UIView Beginanimations:nil Context:null];
[Self setframe:myframe];
[UIView commitanimations];
}

-(void) touchescancelled: (Nsset *) touches withevent: (Uievent *) Event {
/* No State to clean up, so null implementation */
}

6,handle Swipe and drag gestures

Detect swipe
#define Horiz_swipe_drag_min 12
#define VERT_SWIPE_DRAG_MAX 4

-(void) Touchesbegan: (Nsset *) touches withevent: (Uievent *) Event {
Uitouch *touch = [touches anyobject];
Starttouchposition is an instance variable
Starttouchposition = [Touch locationinview:self];
}

-(void) touchesmoved: (Nsset *) touches withevent: (Uievent *) Event {
Uitouch *touch = [touches anyobject];
Cgpoint currenttouchposition = [Touch locationinview:self];

To is a swipe, direction of touch must be horizontal and long enough.
if (FABSF (starttouchposition.x-currenttouchposition.x) >= horiz_swipe_drag_min &&
FABSF (STARTTOUCHPOSITION.Y-CURRENTTOUCHPOSITION.Y) <= Vert_swipe_drag_max)
{
It appears to be a swipe.
if (Starttouchposition.x < currenttouchposition.x)
[Self myprocessrightswipe:touches withevent:event];
Else
[Self myprocessleftswipe:touches withevent:event];
}
}

-(void) touchesended: (Nsset *) touches withevent: (Uievent *) Event {
Starttouchposition = Cgpointzero;
}

-(void) touchescancelled: (Nsset *) touches withevent: (Uievent *) Event {
Starttouchposition = Cgpointzero;
}

Detecting drag gestures
-(void) touchesmoved: (Nsset *) touches withevent: (Uievent *) Event {
Uitouch *atouch = [touches anyobject];
Cgpoint loc = [Atouch locationinview:self];
Cgpoint Prevloc = [Atouch previouslocationinview:self];

CGRect myframe = self.frame;
float deltax = loc.x-prevloc.x;
float DeltaY = loc.y-prevloc.y;
Myframe.origin.x + = DeltaX;
MYFRAME.ORIGIN.Y + = DeltaY;
[Self setframe:myframe];
}

7. Handle mixed multi-touch gestures:

8,hit-testing:

9, Forward Touch event:

Third, gesture recognition:
1,Uigesturerecognizeris aAbstract class, specifically using its subclasses:UITapGestureRecognizer, Uipinchgesturerecognizer (zoom), Uipangesturerecognizer (panning or dragging), Uiswipegestuerrecognizer (swipe in any direction), Uirotationgesturerecognizer (rotate), Uilongpressgesturerecognizer(Long Press)

2, the gesture is attached to a view: For some gestures, byUigesturerecognizer's Locationinview: and Locationoftouch:inview:method to enable the client to find the position of the gesture.

3, Gesture trigger action message:
When a gesture recognizer recognizes its gesture, it sends one or more action messages to one or more targets. When you create a recognizer, you initialize an action and a target, and you can then add more targets-action pairs (byaddtarget:action)

4, discrete gestures and persistent gestures:
When the recognizer recognizes the gesture, it either sends a separate action message or sends multiple action messages until the gesture stops.

5, implement gesture recognition: example:
UITapGestureRecognizer *doublefingerdtap = [[UITapGestureRecognizer alloc] initwithtarget:self action: @selector ( Handledoubledoubletap:)];

The selector function finally has a sender parameter that can be passed into the Uigesturerecognizer
After Uigesturerecognizer is created, you need to use the view's Addgesturerecognizer:, read with the Gesturerecognizers property, use Removegesturerecognizer: Remove.

doublefingerdtap.numberoftapsrequired=2;
Self.theview addgesture ...

6, Response gestures:
discrete gesture omission; persistent gestures, in the gesture processing method, the target object often gets additional information about the gesture. For example, the scale property or the velocity (rate) property.
Example: Handling zoom gestures and handling panning gestures:

-(Ibaction) Handlepinchgesture: (Uigesturerecognizer *) Sender {
CGFloat factor = [(Uipinchgesturerecognizer *) sender scale];
Self.view.transform = Cgaffinetransformmakescale (factor, factor);
}

-(Ibaction) Handlepangesture: (Uipangesturerecognizer *) Sender {
Cgpoint translate = [Sender TranslationInView:self.view];

CGRect newframe = currentimageframe;
Newframe.origin.x + = translate.x;
NEWFRAME.ORIGIN.Y + = Translate.y;
Sender.view.frame = Newframe;

if (sender.state = = uigesturerecognizerstateended)
Currentimageframe = Newframe;
}

7. Interact with other gestures:
More than one gesture may be added to a view, in the default behavior, a touch event in a multi-touch sequence from one gesture recognizer to another, and there is no fixed order until the event is finally delivered to view. Often this default behavior is what you want. But sometimes you may need additional behavior:
1) Let one of the recognizers fail before another recognizer can start analyzing touch events.
2) Prevent other identifiers from analyzing a particular multi-touch sequence or a touch object in that sequence
3) allows two gesture recognizers to operate simultaneously.

Uigesturerecognizer provides client methods, proxy methods, and subclasses overloaded methods to enable you to change these behaviors.

8,requires a gesture recognizer to fail
You callRequiregesturerecognizertofail:。 After the message is sent, the received gesture recognizer must remain in the uigesturerecognizerstatuspossible state until the state of the specified gesture recognizer goes to uigesturerecognizerstatefailed. If the specified gesture state goes to uigesturerecognizerstaterecognized or Uigesturerecognizerstatebegan. Then the receiving recognizer can start, but if it recognizes its gesture, there is no action message sent.

9,prevent gesture recognizers from analyzing touch information
By proxy method or subclass method.
The Uigesturerecognizerdelegate protocol declares two optional methods to prevent the specified gesture recognizer from recognizing gestures on a base-by-base basis:
1) Gesturerecognizershouldbegin: This method is called when a recognizer attempts to change the state uigesturerecognizerstatuspossible. Return no to move it to uigesturerecognizerstatefailed. The default is yes.
2) Gesturerecognizer:shouldreceivetouch: This method is called before the Window object calls the recognizer's touchesbegan:withevent: Returning no indicates that the recognizer is prevented from seeing the object that represents the touch. The default value is yes.

In addition, there are two uigesturerecognizer methods that affect the same behavior:
-(BOOL) Canpreventgesturerecognizer:
-(BOOL) Canbepreventedbygesturerecognizer:

10,allow gesture recognition to be performed simultaneously
By default, no two gesture recognizers can attempt to identify their gestures by a colleague. However, you can change this behavior by implementing an optional method for the proxy: Gesturerecognizer:shouldrecognizesimultaneouslywithgesturerecognizer: Method. Return yes to allow two gesture recognition colleagues to recognize their gestures.
Note: A return of yes means allow, and returning no does not mean that a proxy that prevents simultaneous recognition because of another gesture may return yes.

11, event delivered to views:

12, affect the properties of post touch to views:
You can change the default delivery path by changing the 3 properties of Uigesturerecognizer:
1)Cancelstouchesinview(the default is YES)
2)Delaystouchesbegan(Default is NO)
3)delaystouchesended(the default is YES)

If you change the values of these properties,
1) Cancelstouchesinview set to No, resulting in touchescancalled:withevent: will not be sent to view any touch-during the recognition gesture. As a result, any touch objects that were previously attached to the view that were received at the start or move stage are not valid.
2) Delaystouchesbegan set to Yes ....
3) delaystouchesended set to No ....

13. Create your own gesture recognizer:
1) State transitions:
2) Implement a custom gesture recognizer:

Reprinted from: http://supershll.blog.163.com/blog/static/37070436201273113448804/

Event handling Guide for ios--events driver

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.