无法将手势识别器应用于导航栏
在我的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]
不起作用。
为此,您需要子类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; }
然后,您需要在界面构建器中将导航栏的类名设置为子类的名称。
此外,在导航栏中添加委托协议以监听手势结束时发送的方法也很方便。 例如 – 在上面向右滑动的情况下:
@protocol CustomNavigationbarDelegate - (void)customNavBarDidFinishSwipeRight; @end
然后在m文件中 – 在手势识别方法(无论你做什么)上,你可以触发这个委托方法。
希望这可以帮助
对于其他任何观看此内容的人来说,这是一种更简单的方法。
[self.navigationController.view addGestureRecognizer:oneFingerTwoTaps];