1

我正在尝试创建一个控件,用户可以在其中触摸和移动框架内的按钮。这是我的代码。

- (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event
{

   UITouch *touch = [[event touchesForView:button] anyObject];

    // get delta
    CGPoint previousLocation = [touch previousLocationInView:button];
    CGPoint location = [touch locationInView:button];
    CGFloat delta_x = location.x - previousLocation.x;
    CGFloat delta_y = location.y - previousLocation.y;

    // move button
    button.center = CGPointMake(button.center.x + delta_x,
                                button.center.y + delta_y);   


}

我可以移动按钮(通过触摸和拖动),但是如何限制按钮,使其只能在矩形框架内向左/向右移动。

4

3 回答 3

2

也许这种方法会对你有所帮助。我在不久前制作的一个简单的乒乓球游戏中使用了它。它适用于作为乒乓球游戏弹跳垫的 UIView。我已将反弹垫的移动限制在 x 方向,而不是在屏幕边界之外。

如果有不清楚的地方写评论,我会尽力解释。

// Method for movement of the bouncing pad. Restricted movement to x-axis inside of bounds.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *aTouch = [touches anyObject];
    CGPoint loc = [aTouch locationInView:self];
    CGPoint prevloc = [aTouch previousLocationInView:self];

    CGRect myFrame = self.frame;

    // Checking how far we have moved from the previous location
    float deltaX = loc.x - prevloc.x;

    // Note that we only update the x-position of the pad to prevent it from moving in the y-direction.
    myFrame.origin.x += deltaX;

    // Making sure that the bouncePad cannot move outside of the screen
    if(myFrame.origin.x < 0){
        myFrame.origin.x = 0;
    } else if (myFrame.origin.x + myFrame.size.width > [UIScreen main Screen].bounds.size.width) {
        myFrame.origin.x = [UIScreen mainScreen].bounds.size.width - myFrame.size.width;
    }

    // Setting the bouncing pad frame to the one with the updated position from the touches moved event.
    [self setFrame:myFrame];

}
于 2013-02-07T09:38:10.540 回答
1

如果你想左右移动,你应该只更改X而不是 Y 只需更改如下代码

// move button YOUR CODE
button.center = CGPointMake(button.center.x + delta_x,
                            button.center.y + delta_y);

// move button REMOVED + delta_y
button.center = CGPointMake(button.center.x + delta_x,
                            button.center.y);
于 2013-02-07T09:51:04.353 回答
0

硬编码坐标的极端值或使其在视图中(你的矩形)并使用剪辑来限制您的按钮

于 2013-02-07T09:46:03.130 回答