2014-06-16 75 views
3

因此,進出口讓與的PageControl一個頁面(這是與指示點你是哪個頁面多個視圖的頁面),我的代碼看起來像在viewDidLoad如下:UISwipeGestureRecognizer只有一個方向努力

UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)]; 
UIView *temp = [[UIView alloc]initWithFrame:self.view.frame]; 
temp.backgroundColor = [UIColor clearColor]; 
[temp addGestureRecognizer:swipe]; 
[self.view addSubview:temp]; 

而且在swipeAction選擇我:

- (void)swipeAction: (UISwipeGestureRecognizer *)sender{ 
    NSLog(@"Swipe action called"); 
    if (sender.direction == UISwipeGestureRecognizerDirectionLeft) { 
     //Do Something 
    } 
    else if (sender.direction == UISwipeGestureRecognizerDirectionRight){ 
     //Do Something Else 
    } 
} 

令我驚訝的是,當你滑動到右側(即else if塊被調用)此方法僅適用。當你向左滑動時,swipeAction甚至不會被調用!這很奇怪,爲什麼會發生這種情況,我應該如何更改我的代碼?任何答覆表示讚賞。非常感謝!

+0

該導航控制器內是否帶有此識別器的視圖? –

+0

@SimonGoldeen不,它只是一個普通的'UIView' – ddolce

回答

8

有幾件事你應該知道在這裏。首先,你必須爲你想觀察的每個方向創建一個手勢。這並不是什麼大不了的,因爲你可以簡單地給它們選擇相同的選擇器,它就像兩個方向的一個手勢一樣。

UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)]; 
leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft; 

UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)]; 
rightSwipe.direction = UISwipeGestureRecognizerDirectionRight; 


UIView *temp = [[UIView alloc]initWithFrame:self.view.frame]; 

temp.backgroundColor = [UIColor clearColor]; 
[temp addGestureRecognizer:leftSwipe]; 
[temp addGestureRecognizer:rightSwipe]; 

[self.view addSubview:temp]; 

其次,你從來沒有確定的手勢的方向離開它默認爲右(或1的方向枚舉)

documentation

默認方向是UISwipeGestureRecognizerDirectionRight 。有關更多信息,請參閱UISwipeGestureRecognizerDirection常量的說明。

typedef enum { 
    UISwipeGestureRecognizerDirectionRight = 1 << 0, 
    UISwipeGestureRecognizerDirectionLeft = 1 << 1, 
    UISwipeGestureRecognizerDirectionUp = 1 << 2, 
    UISwipeGestureRecognizerDirectionDown = 1 << 3 
} UISwipeGestureRecognizerDirection; 
+1

如果您使用相同的選擇器操作,則不需要兩個識別器。你可以將它們放在一起,一個識別器將檢測到兩個方向。如果您想對左側或右側滑動進行不同的響應,您將需要兩個識別器。 – joeld

+0

我只是在回答之前嘗試過......它的工作原理。我認爲其他帖子指的是回調,它不會在你的動作中報告方向.swipe.direction仍然會被設置爲left | right,但它會在兩個方向上正確地觸發動作。 – joeld

+1

@joeld我應該稍微改動一下。但是,你能夠通過單一手勢確定滑動的方向嗎? –

0

swipe.direction設置你正在識別的方向,它不會告訴你哪個方向被滑過。創建識別時加入這一行:

swipe.direction = UISwipeGestureRecognizerDirectionLeft|UISwipeGestureRecognizerDirectionRight; 

如果需要檢測哪個方向是刷卡,只需用兩個不同的識別器,一個左,一個右。

+0

感謝回覆@joeld,你絕對正確的是它不會告訴你你刷過哪個方向,但是使用你的代碼,它現在可以識別每個滑動的方向作爲左邊,所以我想唯一正確的方法仍然是有兩個滑動手勢識別器,每個檢測到不同的方向:D – ddolce

+0

不適用於正確的,只是可以檢測。 – Suge