认识到控件拖向哪个方向

时间:2011-02-14 17:29:49

标签: xcode ios4 iphone

想象一下,我在TouchesMoved中拖动一个ImageView,我如何才能识别出我从代码中拖出它的方向?

2 个答案:

答案 0 :(得分:1)

您可以存储来自touchesBegan的临时点。在“YourImageView”界面中添加iVar。

@interface YourImageView : UIImageView
{
    CGPoint previousPt;
    //Other iVars.
}
@end 

@implementation YourImageView

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{   
    previousPt = [[touches anyObject] locationInView:self.view];
}

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    const CGPoint p = [[touches anyObject] locationInView:self.view];
    if (previousPt.x > p.x)
    {
        //Dragged right to left
    }
    else if  (previousPt.x < p.x)
    {
        //Dragged left to right
    }
    else
    {
        //no move
    }
    //Do the same thing for y-direction
}

我会从中提取一个方法。但我希望你有这个主意。

答案 1 :(得分:0)

如果从ImageView的新位置减去旧位置,则会得到方向向量。如果你想要一个单位矢量,只需将其标准化即可。