限制在对角线路径上拖动UIButton

时间:2012-05-01 14:09:50

标签: iphone objective-c xcode ios5 graphics

如何限制按钮的拖动路径,使其只能从我想要的任何位置拖动到屏幕中心?

我知道UIButton的当前位置和中心坐标。 我需要拖拽事件的当前x和y公式。

3 个答案:

答案 0 :(得分: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);

你可以用量级计算来愚弄..最大的组件,最小的,平均的等等。只要结果在两个维度上都是对称的。

答案 1 :(得分:0)

在拖动事件中添加条件。如果它被拖动到你需要的点,那么移动它;否则什么都不做。

答案 2 :(得分:0)

你的意思是:

if ((oldX - newX) < oldX && (oldY - newY) < oldY) {
    updatePosition(newX, newY);
}
相关问题