Search code examples
uiimageviewimageviewuipangesturerecognizerplaysound

Play a sound when UIImageView are inside a specific area


I am moving around some UIImageview with UITouch. I want to play a sound when the image are inside a specific area. What is the easiest way to do that? Thanks for any answer.

// ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize imageView1,imageView2;

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

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

    UITouch *touch = [[event allTouches] anyObject];

    CGPoint touchLocation = [touch locationInView:self.view];

    if ([touch view] == imageView1) { 

        imageView1.center = touchLocation;

    }

    else if ([touch view] == imageView2) {

        imageView2.center = touchLocation;

    }

}

@end

// ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{

    UIImageView *imageView1;

    UIImageView *imageView2;

}

@property(nonatomic,retain) IBOutlet UIImageView *imageView1;

@property(nonatomic,retain) IBOutlet UIImageView *imageView2;

@end

Solution

  • I solved it like this:

    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    
    CGPoint touchLocation = [touch locationInView:self.view];
    NSLog(@"%@", NSStringFromCGPoint(touchLocation));
    
    [self.view bringSubviewToFront:imageView1];
    
    
    if ([touch view] == imageView1) {
    
        imageView1.tag=0;
    
        if ((touchLocation.x >= 340 && touchLocation.x <= 420) && (touchLocation.y  >= 185 && touchLocation.y <= 265)) {
            NSLog(@"head");
    
            [UIView animateWithDuration:0.35
                                  delay:0.0
                                options: UIViewAnimationOptionAllowAnimatedContent
                             animations:^{
                                 imageView1.frame = CGRectMake(380.0-43, 225.0-54, 90.0, 108.0);
                                 imageView1.tag=1;
    
                             }
                             completion:^(BOOL finished){
                                 NSLog(@"Auto justerad!");
                             }];
    
          }
    
       }
    }