如何在移动imageview时将imageview保留在UIView中?

时间:2016-04-19 10:32:19

标签: ios objective-c uigesturerecognizer uitouch

我在主视图控制器中有一个UIView,其中包含1个imageview.i移动的imageview。

 - (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移动完美。但是当我移动时,我必须将UIView内的imageview保留。这段代码的问题是当我移动imageview时它也被移到了UIView之外。我必须将imageview保留在UIView中,并且只能在UIView中移动。 请帮我解决这个问题。如何为imageview设置边界,使其只能在UIView中移动。

2 个答案:

答案 0 :(得分:0)

a)您可以将clipsToBounds的{​​{1}}属性设置为UIView

b)您可以使用暂停代码移动YES

UIImageView

答案 1 :(得分:0)

尝试以下代码。

- (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;

    }
}