0

在谷歌搜索了很多之后仍然没有找到任何解决方案,我在问一个问题。

我的问题是:-我想将我的视图拖动到特定区域,除此之外,我不希望我的视图拖动,但它应该可以在指定的视图中拖动。如果拖动超出,我能够实现停止拖动,但是当我再次触摸它以拖动到允许的区域时,它不会拖动。

My code:-
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {

        UITouch *touch=[touches anyObject];
        CGPoint pt = [[touches anyObject] locationInView:touch.view];
        startLocation = pt;
    }

    - (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
        // Move relative to the original touch point
        UITouch *touch=[touches anyObject];
        CGPoint pt = [[touches anyObject] locationInView:touch.view];
        CGPoint pt2 = [[touches anyObject] locationInView:self.view];

        if ([touch.view isKindOfClass:[MyView class]]) {

            CGRect frame = [touch.view frame];
            CGRect prevFrame=[touch.view frame];
            frame.origin.x += pt.x - startLocation.x;
            frame.origin.y += pt.y - startLocation.y;
            CGRect boundsA = [touch.view convertRect:touch.view.bounds toView:nil];
            CGRect boundsB = [self.canvasVw convertRect:self.canvasVw.bounds toView:nil];

                Boolean viewsOverlap = CGRectContainsRect(boundsB,boundsA );
                if (viewsOverlap==YES) {
                    NSLog(@"intersects");
                    [touch.view setFrame:frame];

                }
                else{
                    NSLog(@"not intersects");


    }
        }
      }

代码中的问题是假设我拖动视图,并且它超出了该区域,然后它不再拖动。

看图片:- 在此处输入图像描述

我只需要在白色区域而不是黑色区域拖动红色视图。请建议我如何做到这一点。谢谢。

4

1 回答 1

1

好吧,基本上,边界。尽管看起来很无聊,但请确保:

  • 红色的 self.frame.position.x 不是 < 0 (零是其父级的位置)
  • self.frame.position.x + self.frame.size.width 不大于 self.superview.size.width

Y的逻辑相同。


编辑1:

double possibleNewX = pt.x - startLocation.x;

if (((self.frame.position.x + possibleNewX) > 0) && ((self.frame.size.width + self.frame.position.x + possibleNewX) < self.superview.frame.size.width))
{
   frame.origin.x += possibleNewX;
}

double possibleNewY = pt.y - startLocation.y;

if (((self.frame.position.y + possibleNewY) > 0) && ((self.frame.size.height + self.frame.position.y + possibleNewY) < self.superview.frame.size.width))
{
   frame.origin.y += possibleNewY;
}
于 2012-11-13T18:02:54.510 回答