0

How can I constrain the drag-path of a button so that it can only be dragged to the centre of the screen from any point I want?

I know the current position of the UIButton and the centre coordinates. I need the current x and y formula for the drag event.

4

3 回答 3

2

这应该这样做。保存拖动的开始位置,获取每个移动事件的当前位置。将它们传递给这个函数。它将回答一个可以应用于按钮框架的向量。

计算的要点是通过选择阻力的最小分量(x 或 y)并回答在两个维度上具有相同大小的向量(保留两个轴上的符号)来确定大小。

// answer a vector to apply to an object's frame, constrained to a diagonal
- (CGPoint)constrainToDiagonalFrom:(CGPoint)from to:(CGPoint)to {

    CGPoint diff = CGPointMake(to.x-from.x, to.y-from.y);
    CGFloat magnitude = MIN(fabs(diff.x), fabs(diff.y));    // this is how large the drag will be
    return CGPointMake(copysignf(magnitude, diff.x), copysignf(magnitude, diff.y));
}

像这样称呼它:

// on touches moved
// we saved startPoint on touches began
// get location from this event's touches

CGPoint diagonal = [self constrainToDiagonalFrom:startPoint to:location];
myButton.frame = CGRectOffset(myButton.frame, diagonal.x, diagonal.y);

您可以随意计算幅度。最大分量,最小分量,平均值等。只要结果在两个维度上都是对称的。

于 2012-05-01T14:44:08.883 回答
0

你的意思是像:

if ((oldX - newX) < oldX && (oldY - newY) < oldY) {
    updatePosition(newX, newY);
}
于 2012-05-01T14:43:58.070 回答
0

在拖动事件中放置一个条件。如果它被拖动到您需要的位置,则移动它;否则什么都不做。

于 2012-05-01T14:34:22.597 回答