Search code examples
iosobjective-cuigesturerecognizeruitouch

How to keep imageview inside UIView when moving imageview?


I have an UIView inside main view controller which contain 1 imageview.i moved imageview with this method.

 - (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
   UITouch *aTouch = [touches anyObject];
   if (aTouch.view == self.sub_View) {
    CGPoint location = [aTouch locationInView:self.sub_View];
    CGPoint previousLocation = [aTouch previousLocationInView:self.sub_View];
    self.imageView.frame = CGRectOffset(self.imageView.frame, (location.x - previousLocation.x), (location.y - previousLocation.y));
    }
}

Imageview move perfect. But i have to keep imageview inside UIView when i moved. Problem with this code is when i move imageview it is also moved outside UIView. I have to keep imageview inside UIView and movable only inside UIView. Please help me to solve this. How to set boundary for imageview so it is movable only inside UIView.


Solution

  • Try below code.

    - (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
    {
       UITouch *aTouch = [touches anyObject];
       if (aTouch.view == self.sub_View) {
        CGPoint location = [aTouch locationInView:self.sub_View];
        CGPoint previousLocation = [aTouch previousLocationInView:self.sub_View];
        CGRect newFrame = CGRectOffset(self.imageView.frame, (location.x - previousLocation.x), (location.y - previousLocation.y));
        if(newFrame.origin.x < 0)
             newFrame.origin.x = 0;
        if(newFrame.origin.y < 0)
             newFrame.origin.y = 0;
        if(newFrame.origin.x + newFrame.size.width > self.frame.size.width)
             newFrame.origin.x = self.frame.size.width - self.imageView.frame.size.width;
        if(newFrame.origin.y + newFrame.size.height > self.frame.size.height)
             newFrame.origin.y = self.frame.size.height - self.imageView.frame.size.height;
    
        self.imageView.frame = newFrame;
    
        }
    }