【问题标题】:Dragging an view in limited boundaries not beyond that在有限边界内拖动视图而不超出该边界
【发布时间】:2012-11-13 17:50:09
【问题描述】:

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

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

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


    }
        }
      }

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

看图:-

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

【问题讨论】:

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


    【解决方案1】:

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

    • 红色的self.frame.position.x不是
    • 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;
    }
    

    【讨论】:

    • 能否请您详细说明编码术语。
    • 检查我的编辑。我是从头顶上做的,如果有错别字,对不起。
    • 这个答案对我来说确实很有吸引力,但我必须实现旋转和拖动功能现在如果我旋转我的视图然后拖动它,它会显示有线行为。请你帮我解决这个问题。
    • 旋转,是处理UIView的Auto-size mask的问题,玩一下,不熟。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多