2012-06-23 18 views
4

在我的iPad應用程序中,我在屏幕上顯示了多個視圖。將手勢識別器應用到導航欄時遇到問題

我想要做的是將雙擊手勢識別器應用於導航欄。但是,我沒有成功,但是當相同的手勢識別器適用於該視圖時,它就起作用了。

這裏是我使用的代碼:

// Create gesture recognizer, notice the selector method 
UITapGestureRecognizer *oneFingerTwoTaps = 
[[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(oneFingerTwoTaps)] autorelease]; 

// Set required taps and number of touches 
[oneFingerTwoTaps setNumberOfTapsRequired:2]; 
[oneFingerTwoTaps setNumberOfTouchesRequired:1]; 

[self.view addGestureRecognizer:oneFingerTwoTaps]; 

這部作品的看法,但如果這樣做:

[self.navigationController.navigationBar addGestureRecognizer:oneFingerTwoTaps] 

不起作用。

回答

4

爲此,您需要繼承UINavigationBar,覆蓋它中的init按鈕並在其中添加您的手勢識別器。

所以說你犯了一個名爲「CustomNavigationBar」子類 - 在M檔,你將有一個init方法是這樣的:

- (id)initWithCoder:(NSCoder *)aDecoder 
{ 
    if ((self = [super initWithCoder:aDecoder])) 
    { 
     UISwipeGestureRecognizer *swipeRight; 
     swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipeRight:)]; 
     [swipeRight setDirection:UISwipeGestureRecognizerDirectionRight]; 
     [swipeRight setNumberOfTouchesRequired:1]; 
     [swipeRight setEnabled:YES]; 
     [self addGestureRecognizer:swipeRight]; 
    } 
    return self; 
} 

然後,你需要設置在界面生成器的導航欄的類名到你的子類的名字。

enter image description here

而且它很方便的一個委託協議添加到您的導航欄聽在你的手勢結束時發送的方法。例如 - 在上面輕掃權的情況下:

@protocol CustomNavigationbarDelegate <NSObject> 
    - (void)customNavBarDidFinishSwipeRight; 
@end 

然後在M檔 - 對手勢識別的方法(無論你把它),你可以觸發這個委託方法。

希望這有助於

+0

:非常感謝您的解決方案。實際上,我努力嘗試。相反,我在導航欄上添加了一個自定義按鈕,並將該手勢識別器添加到按鈕中。我知道這不是正確的方法,但它做了工作:) – Shantanu

+0

不應該在'initWithCoder'方法中返回'self' ? – bompf

+0

你應該 - 我想我忘了補充一點:P *現在編輯 –

8

對於其他人查看此,這裏是一個更簡單的做到這一點的方式。

[self.navigationController.view addGestureRecognizer:oneFingerTwoTaps]; 
+0

更快的解決方案! –