如何向 NavigationBar 的标题添加操作?

How I can add action to title of NavigationBar?

我想give/add对导航标题的标题进行操作。 (例如“探索”)

我想使用这种方法执行一些 activity。

我尝试了以下代码,但它不起作用。

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self
               action:@selector(touchedOnNavigationTitle:)
     forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Explore" forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 100, 100);
    //[view addSubview:button];
    [self.navigationItem.titleView addSubview:button];

-(void)touchedOnNavigationTitle:(UIButton*)sender {
    NSLog(@"Clicked on Navigation Title");
}

ViewController 名称来自当前 ViewController 类型而不是 push.navigationController 堆栈。

如何使用 objective-C 代码实现此目的?

titleView默认为nil

https://developer.apple.com/documentation/uikit/uinavigationitem/1624935-titleview

您应该使用按钮设置标题视图。不将其添加为子视图。

self.navigationItem.titleView = button

用以下代码替换您的代码:

UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button addTarget:self
           action:@selector(touchedOnNavigationTitle:)
 forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Explore" forState:UIControlStateNormal];
self.navigationItem.titleView = button;

-(void)touchedOnNavigationTitle:(UIButton*)sender {
    NSLog(@"Clicked on Navigation Title");
}