So here is a quick post on how to work with a UITouch. This tutorial will put a UIImageView on a view and then when you touch around the image view will be placed where you touch.
So lets start out by creating a new project and and use a View Based application as shown below.
Now I called the project touch.
So lets create an outlet for the image view we will create. So open up touchViewController.h. Add your outlet.
IBOutlet UIImageView *image;
Now take a image and drag it into your project. For this I will use the following image.
Now double click on touchViewController.xib and it will load IB. Take a UIImageView and drag it on the view. You also want to set the image to the image you dragged to your project. Your view should now look something like this
Now create the link from the outlet you created to the view so it looks like this in the File’s Owner.
Now save the file and quit. If you clicked build and go now we will just see a box on the screen and it does nothing. So we need to add in a function to handle the touch.
So open up touchViewController.m and add in the following code.
// get touch event
UITouch *touch = [[event allTouches] anyObject];
// get the touch location
CGPoint touchLocation = [touch locationInView:touch.view];
// move the image view
image.center = touchLocation;
So pretty much we are grabbing a touch even on any object it may touch. Then we are getting the location of the touch. We will then take that and move the image.
The thing that sent me for a loop is the locationInView accepts a UIView so I was wondering why self.view didn’t work. I still have no clue but touch includes the view that was touched and that seems to work nicely.
The Apple code works off sub-classing your view which I have never done but this seems to work nicely.
As always here is the source code.