n iPhone/iPad app, touch is the most common action. Here,I am describing touch events and a simple way to attach it with image view and with the help of touch events, images will move left/right when user swipe on the image i.e. if one swipe from left to right, image to left of the current image appears on the screen and vice-versa.
Also, the images will move in a circular loop i.e. swipe on last image advances to first image.
The idea is to present the image view with added feature of scrolling.
–Go to File>NewProject>ViewBasedApplication and enter the name the project.I have taken the name as “ImageTouch”.
–Next, go To File>NewFile and choose ObjectiveC class and also make it subclass of UIView.Then click choose and enter FileName and I have taken as “TouchImageView”.
–Next go to nib file that is created i.e. “ImageTouchViewController.xib” and open it and select the view, change its class to “TouchImageView”.
–Now, drag “ImageView ” in the view of nib file.
@interface TouchImageView : UIView
@property (nonatomic, retain) NSMutableArray* _imagesArray;
@property(nonatomic,retain) IBOutlet UIImageView* _imgView;
_imageArray is used to store images as object.
_keyIndex :the index of the image to be displayed.
_currentPoint: X-coordinate of the point where touch began.
_movedPoint: X-coordinate of the point where touch ended.
_IsMoved : To indicate whether the image has been swapped or not.
In TouchImageView.m, I will describe initialization step and touch events:
// Index initialization
This function will initialize the array with image objects.And set the a default image in imageView .I have taken default index as 0.
Touch events implemented are as : touchesBegan,touchesMoved,touchesEnded.
You must be sure to call the superclass implementation (super) in all of the methods you override.
This event triggers when user touches the view .And once it triggers, the first point where the touch has began is stored in _currentPoint.Following is the code:
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
UITouch* touch = [[event allTouches] anyObject];
CGPoint touchedPoint = [touch locationInView:self];
_currentPoint = (int)touchedPoint.x;
Here,_currentPoint stores the x-coordinate of the point where the touch has began.
This event triggers only if user swipe on the screen.
And _IsMoved is used to check whether this event is fired or not.
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
// Move relative to the original touch point
CGPoint pt = [[touches anyObject] locationInView:self];
This event is fired when the touch ends.
Now,_IsMoved value is used to check whether the touchesMoves event was triggered or not.
If it is true then which image to be placed is calculated on the basis of _currentPoint and _movedPoint.
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
Here, if the _keyIndex reaches the max value then it is set to zero making the images to move in a circular loop.
And now the images moves on swipe!!!