Search Posts in my Blog

Wednesday 7 March 2012

Actions on image touch



Sometimes it may happen that you need to touch the images and on the touch of a specific image you need to perform some action.

So in todays post we shall discuss how to do this.

Design Phase: For this demo i took two image views containing the images of spider man and super man and on the touch of each image i will display an UIAlertview.



Step 1: open Xcode and create a windows based application and add the UIViewController subclass file into it with an appropriate name, now create the view just like the above image of the design phase containing two instance of UIImageView class.

Step 2: Once you have completed the design now its time to add the instance method of the UIResponder class called as the touch began

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


Step 3: It's time to give body to that method, the entire code looks like this

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
pnt = [[touches anyObjectlocationInView:self.view];
if (CGRectContainsPoint(SpiderManImageView.framepnt)) 
{
UIAlertView *spiderManAlertView = [[UIAlertView alloc]initWithTitle:@"iPhone-RahulVarma" message:@"Spider man image touched" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok",nil];
[spiderManAlertView show];
[spiderManAlertView release];
}
else if(CGRectContainsPoint(SupermanImageView.framepnt))
{
UIAlertView *superManAlertView = [[UIAlertView alloc]initWithTitle:@"iPhone-RahulVarma" message:@"Super man image touched" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok",nil];
[superManAlertView show];
[superManAlertView release];
}
}


Code Explanation: The CGRectContainspoint is a function which accepts 2 parameter one is the rectangle who's points are to be examined and other is the parameter for the examiner point that will be checked and then just apply a simple if clause. The pnt is a variable of type CGPoint which contains the information about the point where the user has currently touched.

Step 4: Select the appDelegate.m file and this view to the iPhone window and then run the application.

Step 5: When you run the application you will get the final output. See the magic implementation.


I hope that this post was helpful to you

No comments:

Post a Comment