Multiple Objects and UITouch

September 22, 2008    iphone Programming uiimageview UITouch

Here is a bit of a continuation of Working with UITouch

Please follow that tutorial first. We will be using the source code from that as our starting point. So once you have the source code in Xcode open up touchViewController.h and we need to add in one new outlet for our second image.

So we want the file to look like this. I have commented the line I have added in.

#import <UIKit/UIKit.h>
@interface touchViewController : UIViewController {
    IBOutlet UIImageView *image;
    IBOutlet UIImageView *image2; // added this
}

@end

Now we need to open up IB and create the new object and make the connection. Double click on touchViewController.xib. So my view now looks like this

My connections now look like this

Also we need to set something for the views in order for a click and drag to work on them. We need to make sure user interaction is enabled on the two UIImageViews we have in our main view. So the property for one looks like the following. Make sure you set this for both image views

Now you can save your view in IB and load up touchViewController.m. In our previous example we had the following method.

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    // 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;
}

You can now either comment out that function or delete it. We don’t want to use it anymore. Instead add in the following method.

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    // get touch event
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    if ([touch view] == image) {
        // move the image view
        image.center = touchLocation;
    }
    else if ([touch view] == image2) {
        // move the image view
        image2.center = touchLocation;
    }
}

That function will now allow you to click on a imageview and hold the click and drag the image around the screen.

As always you can grab the source code here.



comments powered by Disqus