2012-11-22 50 views
2

我的窗口上有兩個UIViews:一個用來保存玩家分數,(側邊欄)和一個主要玩區域。它們都適合UIWindow,既不滾動。用戶可以在主要遊戲區域拖動UIButtons - 但目前,他們可以將它們拖放到側邊欄上。一旦他們這樣做了,他們就不能再拖拽它們,大概是因爲你在第二個視圖上敲擊,而第二個視圖不包含有問題的按鈕。防止在UIView之外拖動UIButton

我想阻止主視圖內的任何內容移動到側欄視圖中。我管理好了這一點,但是如果玩家的手指離開視圖,我需要釋放拖動。使用下面的代碼,按鈕會隨着手指一直移動,但不會超過視圖的X座標。我怎麼去解決這個問題?

[firstButton addTarget: self action: @selector(wasDragged: withEvent:) forControlEvents: UIControlEventTouchDragInside]; 

這種方法:拖動時,使用此調用啓用

- (void) wasDragged: (UIButton *) button withEvent: (UIEvent *) event 
{ 
    if (button == firstButton) { 
     UITouch *touch = [[event touchesForView:button] anyObject]; 
     CGPoint previousLocation = [touch previousLocationInView:button]; 
     CGPoint location = [touch locationInView:button]; 
     CGFloat delta_x = location.x - previousLocation.x; 
     CGFloat delta_y = location.y - previousLocation.y; 
     if ((button.center.x + delta_x) < 352) 
     { 
      button.center = CGPointMake(button.center.x + delta_x, button.center.y + delta_y); 
     } else { 
      button.center = CGPointMake(345, button.center.y + delta_y); 
     } 
    } 
} 

回答

0

實施

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

觸摸委託方法,然後檢查UITouch的位置,如果該位置超出了你想允許的界限(第一個視圖),那麼不要再進一步移動它。您也可以在用戶在視圖外拖動的位置使用 iVar

//In .h file 
BOOL touchedOutside; 

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    touchedOutside = NO; 
} 

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    if (!touchedOutside) { 
     UITouch *touch = [[event allTouches] anyObject]; 
     CGPoint location = [touch locationInView:firstView]; 

      if (location.x < UPPER_XLIMIT && location.x > LOWER_XLIMIT) { 
       if (location.y < UPPER_YLIMIT && location.x > LOWER_YLIMIT) { 

        //Moved within acceptable bounds 
        button.centre = location; 
       } 
      } else { 
       //This will end the touch sequence 
       touchedOutside = YES; 

       //This is optional really, but you can implement 
       //touchesCancelled: to handle the end of the touch 
       //sequence, and execute the code immediately rather than 
       //waiting for the user to remove the finger from the screen 
       [self touchesCancelled:touches withEvent:event]; 
    } 
}