繁体   English   中英

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

[英]How I can add action to title of NavigationBar?

我想为导航标题的标题提供/添加操作。 (例如“探索”)

在此处输入图像描述

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

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

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 名称来自 presentViewController 类型而不是来自 push.navigationController 堆栈。

如何使用 objective-C 代码实现这一点?

将您的代码替换为以下内容:

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");
}

titleView默认为nil

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

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

self.navigationItem.titleView = button

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM