如何检测滑动方向?

时间:2014-05-01 10:40:25

标签: ios objective-c cocoa-touch swipe

我想检测用户何时进行滑动手势,并检测其方向(左,右,上或下)。我需要在手势结束时检测到它,但是当iPhone知道方向时,即使它没有完成。

我正在使用XCode 5,并使用iOS 7为iPhone 5进行设计。

我想知道我必须粘贴到.h和.m的代码,如果我必须将任何项目拖放到mainView。

5 个答案:

答案 0 :(得分:4)

如果您想知道手势未完成的方向,您可能需要UIPanGestureRecognizer并使用velocityInView:方法检测方向。

* .h文件中的

@interface ViewController : UIViewController

@property (nonatomic, strong) UIPanGestureRecognizer *recognizer;

@end
* .m文件中的

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];

    [self.view addGestureRecognizer:self.recognizer];
}

-(void)panGesture:(UIPanGestureRecognizer *)sender
{
    NSLog(@"Velocity: %@", NSStringFromCGPoint([sender velocityInView:self.view]));

    // Here You need to determine the direction
}
@end

答案 1 :(得分:0)

您可以轻松使用UISwipeGestureRecognizer属性指示... 之后:----

    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeRight)];
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
    [self.yourView addGestureRecognizer:swipeRight];
    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeLeft)];
    swipeRight.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.gifWebView addGestureRecognizer:swipeLeft];

-(void)swipeRight{
//Do whatever you want
}
-(void)swipeLeft{
//Do whatever you want
}

对于之前的滑动,您可以使用UITapGestureRecognizer

我希望它可以帮到你

答案 2 :(得分:0)

来自Docs

  

手势是离散的或连续的。这是一个离散的手势   作为点击,发生一次。连续的手势,如捏,需要   放置一段时间。对于离散手势,手势   识别器向目标发送单个操作消息。一个手势   用于连续手势的识别器持续发送动作消息   它的目标直到多点触控序列结束,

因此,如果您需要“在手势完成时检测到它,而且只是当iPhone知道方向时,即使它没有完成”,您也无法使用UISwipeGestureRecognizer,因为它是一个离散的。您应该使用UIPanGestureRecognizer并分析结果以检查是否有滑动手势。

答案 3 :(得分:0)

为了有一个很好的例子,你可以下载Apple提供的示例代码:

https://developer.apple.com/library/ios/samplecode/SimpleGestureRecognizers/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009460

希望有所帮助;)

答案 4 :(得分:0)

滑动手势非常快。滑动手势识别器设计为可以触发一次,而不是连续触发。我认为您无法轻易获得有关“飞行中”滑动手势的信息。

如果这很紧急,您可能必须创建滑动手势识别器的自定义子类,并添加其他逻辑和委托消息,一旦手势识别器确定已检测到滑动,就会通知代理。但这远远超出了你目前的技术水平。

相关问题