How to Move Image using Touch Function in iPhone?


This is the very simple application. In this application we will see how to image move using touch. So let see how it will work.

Step 1 : Open the Xcode, Create a new project using View Base application. Give the application “Touch_Image”.

Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the directory structure to check out the content of the directory.

Step 3: We need add also two resource in the project.

Step 4: In the Touch_ImageViewController.h file, make the following changes.

#import <UIKit/UIKit.h> 

@interface Touch_ImageViewController : UIViewController {
UIImageView *image;
}
@property (nonatomic,retain) IBOutlet UIImageView *image;
@end

Step 5: Double click the Touch_ImageViewController.xib file and open it to the interface builder. First select the view and bring up Attribute Inspector and change the background color. Drag the label from the library and place it to the view window. Select the label and bring up Attributes Inspector and the text to “Touch Anywhere” . Now drag the ImageView from the library and place it to the view window. Select the Image View from the view and bring up Attribute Inspector and select the litchi-big.png image. Connect File’s Owner icon to the image view and select image. Now save the .xib file, save it and go back to the Xcode.

Step 6: Open the Touch_ImageViewController.m file and make the following changes:

#import “Touch_ImageViewController.h” 

@implementation Touch_ImageViewController

@synthesize image;

– (void)dealloc
{
[super dealloc];
}

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{

UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:touch.view];
image.center = touchLocation;
}

– (void)didReceiveMemoryWarning
{

[super didReceiveMemoryWarning];

}

#pragma mark – View lifecycle

– (void)viewDidUnload
{
[super viewDidUnload];
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

 

Step 7: Now compile and run the application on the Simulator.