UINavigationBar Touch

moo*_*ots 21 iphone cocoa-touch uinavigationbar uikit ios

当用户点击我的一个视图的导航栏标题时,我想触摸一个事件.

我是否可以访问UINavigationBar标题的视图,以便将触摸事件连接到它,我有点不知所措.

这甚至可能吗?

小智 43

您可以添加手势识别器,只需点击一下导航控制器的标题即可.我发现在navigationBar子视图中,标题是索引1的标题,左键的索引是0,右键的索引是2.

UITapGestureRecognizer *navSingleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(navSingleTap)];
navSingleTap.numberOfTapsRequired = 1;
[[self.navigationController.navigationBar.subviews objectAtIndex:1] setUserInteractionEnabled:YES];
[[self.navigationController.navigationBar.subviews objectAtIndex:1] addGestureRecognizer:navSingleTap];
Run Code Online (Sandbox Code Playgroud)

然后在您的实现中的某处实现以下内容.

-(void)navSingleTap
Run Code Online (Sandbox Code Playgroud)

因此,您可以将其用于单击,或者您可以在该标题上实现您想要的任何手势识别器.


小智 30

我找到的解决方案是一个按钮,我使用以下(但我不知道它是如何"合法"):

UIButton *titleLabelButton = [UIButton buttonWithType:UIButtonTypeCustom];
[titleLabelButton setTitle:@"myTitle" forState:UIControlStateNormal];
titleLabelButton.frame = CGRectMake(0, 0, 70, 44);
titleLabelButton.font = [UIFont boldSystemFontOfSize:16];
[titleLabelButton addTarget:self action:@selector(didTapTitleView:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.titleView = titleLabelButton;
Run Code Online (Sandbox Code Playgroud)

把那些代码放在你设置标题的地方.然后我在其他地方测试:

- (IBAction)didTapTitleView:(id) sender
{
    NSLog(@"Title tap");
}
Run Code Online (Sandbox Code Playgroud)

在控制台上记录了"标题点击"!

我这样做的方式可能完全错误,但可能会让你知道你可以看到什么.这肯定帮助了我!尽管如此,可能还有更好的方法.


Rik*_*nna 25

其他答案都不适合我.而不是将一个手势添加到navigationBar的现有子视图,或者替换titleView,我只是添加了一个清晰的UIView,覆盖了导航栏的很大一部分......

- (void) setupNavbarGestureRecognizer {
    // recognise taps on navigation bar to hide
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showHideNavbar)];
    gestureRecognizer.numberOfTapsRequired = 1;
    // create a view which covers most of the tap bar to
    // manage the gestures - if we use the navigation bar
    // it interferes with the nav buttons
    CGRect frame = CGRectMake(self.view.frame.size.width/4, 0, self.view.frame.size.width/2, 44);
    UIView *navBarTapView = [[UIView alloc] initWithFrame:frame];
    [self.navigationController.navigationBar addSubview:navBarTapView];
    navBarTapView.backgroundColor = [UIColor clearColor];
    [navBarTapView setUserInteractionEnabled:YES];
    [navBarTapView addGestureRecognizer:gestureRecognizer];
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*lds 9

UINavigationItem类引用有一个titleView属性,它可以设置为自定义UIView.

换句话说,UIView使用触摸处理程序创建子类,然后在推送导航项时,将该项的titleView属性设置为子类的实例.