2

我的窗口上有两个 UIView:一个用于保存玩家分数,(一个侧边栏)和一个主游戏区。它们都适合 UIWindow,并且都不滚动。用户可以在主播放区域上拖动 UIButtons - 但目前,他们可以将它们拖放到侧边栏上。一旦他们这样做了,他们就不能再次拖动它们以将它们带回来,大概是因为您正在点击第二个视图,该视图不包含相关按钮。

我想防止将主视图内的任何内容移动到侧边栏视图上。我已经做到了,但是如果玩家的手指离开该视图,我需要释放拖动。使用下面的代码,按钮会随着手指移动,但不会越过视图的 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);
        }
    }
}
4

1 回答 1

0

实施

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

touch 委托方法,然后检查 的位置UITouch,如果该位置超出了您要允许的范围(第一个视图),则不要再移动它。您还可以使用BOOLiVar在用户拖动到视图外的点终止触摸

//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];   
    }
}
于 2012-11-22T17:26:47.860 回答