简体   繁体   中英

How I can add action to title of NavigationBar?

I want to give/add action to the title of navigation title. (Example "Explore")

在此处输入图像描述

I want to perform some activity using this approach.

I tried following code, but it's not working.

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 name is came from presentViewController type not from push.navigationController stack.

How I can achieve this using objective-C code?

Replace your code with the following:

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 is nil by default.

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

You should set your title view with your button. Not add it as a subview.

self.navigationItem.titleView = button

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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