Question

I'm trying to create a simple application where you can move your UIImageView by touching him and dragging him around.

my UIImageView is called imv

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

UITouch * touch = [touches anyObject];

if([touch view] == self.imv){
    CGPoint location = [touch locationInView:self.view];
    self.imv.center = location;

}
}

-(void ) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch * touch = [touches anyObject];

if([touch view] == self.imv){
    CGPoint location = [touch locationInView:self.view];
    self.imv.center = location;

}
}

i'am trying to solve this like whole day and i don't know what is wrong. If i disable if statement it's working else not. What can i do?

Thanks for the answers

Was it helpful?

Solution

Unless you've subclassed UIImageView (unlikely), your view is receiving the touch events.

These days it's simpler & more usual to use a UIGestureRecognizer for this kind of thing, in this case a UIPanGestureRecognizer.

e.g.

UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragImageView:)];
[self.imv addGestureRecognizer:pan];


- (void)dragImageView:(UIPanGestureRecognizer *)dragImageView {
    if(UIGestureRecognizerStateBegan  == state) {
        originalCenter = self.imv.center;    // add CGPoint originalCenter; member
    } else if(UIGestureRecognizerStateChanged == state) {
        CGPoint translate = [pan translationInView:self.imv.superview];
        self.imv.center = CGPointMake(originalCenter.x + translate.x, originalCenter.y + translate.y);
    }
}

OTHER TIPS

From a bit of experimenting, it seems that the [touch view] is returning the main UIView and not your subview, hence the problem with the if statement not working (I added the UIImageView in a storyboard xib). EDIT- it's because UIImageViews don't handle touch events by default - see here . When adding a regular UIView in the viewDidLoad seems to work as you would expect.

Anyway, this adapted version of your code works for me

-(void)moveImageForTouches:(NSSet*)touches
{
    UITouch * touch = [touches anyObject];
    CGPoint location = [touch locationInView:self.view];

    if(CGRectContainsPoint(self.imv.frame, location))
    {
        self.imv.center = location;
    }

}

-(void ) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self moveImageForTouches:touches];
}

-(void ) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self moveImageForTouches:touches];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top