2012-11-13 40 views
0

經過Google搜索並仍未找到任何解決方案之後,我提出了一個問題。在有限範圍內拖動視圖不會超出該範圍

我的問題是: - 我想拖動我的視圖在一個特定的區域,除此之外,我不希望我的視圖拖動,但它應該可拖動在指定的視圖。 我能夠實現停止拖動,如果拖動超過,但我再次觸摸拖動它在允許的區域拖動它不會拖動。

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


    } 
     } 
     } 

在代碼的問題是想拖我的觀點,並進入該地區之外,那麼就不會再次拖累。

看到圖像: - enter image description here

我需要拖動紅色視圖只白色區域沒有黑色區域。 請告訴我如何做到這一點。 謝謝。

回答

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; 
} 
+0

能否請您在編碼方面詳細說明。 – Gypsa

+0

檢查我的編輯。我是從頭頂上做的,對不起,如果有錯字。 – Peres

+0

答案對我來說真的很有用,但我必須實現旋轉和拖動功能。現在,如果我旋轉了視圖然後拖動它,它就會顯示有線行爲。請你幫我解決這個問題。 – Gypsa