Thứ Sáu, 11 tháng 4, 2014

Gesture recognizers in iOS


In this blog post, we’ll look at the built – in touch gesture recognizers that can be accessed using Interface Builder in Xcode. These gestures include taps, pinches, rotations, swipes, pans, and long presses, which should be sufficient for most developer needs. They are as simple as a control to add to the app, and should be used whenever one of these simple gestures is required in our applications. So, let’s get started.


Start Xcode and create a new app named Gestures using the single view application template. Open the main.storyboard file, and add a label to the view as shown:


image0205141


Drag a tap gesture recognizer and a swipe gesture recognizer to the view:


image0205142


Now open up ViewController.h and add two action methods for these recognizers as shown:










































1


2


3


4


5


6


7


8




#import <UIKit/UIKit.h>


 


@
interface

ViewController

:

UIViewController


 


-

(
IBAction
)
tapGesture
:
(
UITapGestureRecognizer *
)
sender
;


-

(
IBAction
)
swipeGesture
:
(
UISwipeGestureRecognizer *
)
sender
;


 


@
end





Sender in each case is typed to the UIGestureRecognizer subclass we’re interested in. If we had left these typed to “id,” sender would need to be cast to the proper subtype in the method body. This approach is simpler.


Next add the method bodies for these actions to ViewController.m:










































1


2


3


4


5


6


7


8


9




-

(
IBAction
)
tapGesture
:
(
UITapGestureRecognizer *
)
sender


{


    
self
.
view
.
backgroundColor

=

[
UIColor
redColor
]
;


}


 


-

(
IBAction
)
swipeGesture
:
(
UISwipeGestureRecognizer *
)
sender


{


    
self
.
view
.
backgroundColor

=

[
UIColor
greenColor
]
;


}





In this case, we are simply changing the background color of the main view. The code here can be as simple or complex as needed: we could do virtually anything in response to a touch gesture.


The final step is to wire up these methods to their corresponding recognizers in Interface Builder as shown:


image0205143


Run the app, then tap the screen. The color changes to red:


image0205144


Swiping the screen causes the view color to change to green:


image0205145


If we are adding gesture recognizers to controls that do not normally accept touch gestures (such as image views, for instance), we must make sure to enable user interaction for those controls in the attribute inspector.


Try different combinations of controls and gesture recognizers to see what works. And as always, have fun!











Did you enjoy this article?








Share


the


Love







Get Free Updates









































Source : edumobile[dot]org

Không có nhận xét nào:

Đăng nhận xét