防止在UIView之外拖动UIButton

时间:2012-11-22 15:05:12

标签: objective-c ios cocoa-touch uiview uitouch

我的窗口上有两个UIViews:一个用于保持玩家得分,(侧边栏)和一个主要游戏区域。它们都适合UIWindow,而且都不会滚动。用户可以在主游戏区域上拖动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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

实施

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

触摸委托方法,然后检查UITouch的位置,如果位置超出您想要允许的范围(第一个视图),则不要再移动它。您还可以使用BOOL 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];   
    }
}