iphone - 在有限的边界内拖动 View 而不超出该边界

标签 iphone objective-c ios drag-and-drop touchesmoved

经过多次谷歌搜索后仍然没有找到任何解决方案,我提出一个问题。

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

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");


    }
        }
      }

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

看图片:- enter image description here

我需要仅将红色 View 拖动到白色区域而不是黑色区域。 请建议我如何做到这一点。 谢谢。

最佳答案

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

  • 红色的 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;
}

关于iphone - 在有限的边界内拖动 View 而不超出该边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13365964/

相关文章:

iphone - 如何停止使用 CSS 进行背景分层?

iphone - 使用CGPath画一条线

ios - 在 iOS 的 tableview 中动态搜索

objective-c - 以编程方式居中 UIButton

ios - Alamofire HTTPS 请求失败

iphone - 如何在iPhone中实现DS数字字体

iphone - 新手 : Errors in an iPhone app

ios - 根据名称或包标识符获取 iOS 应用程序的路径

iphone - 我怎么知道 AppDelegate 中的方向发生了变化

IOS:从数组中将字符串写入文件txt