Nikita Patil
Nikita Patil

Reputation: 724

How I can add action to title of NavigationBar?

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

enter image description here

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?

Upvotes: 0

Views: 548

Answers (2)

The Mach System
The Mach System

Reputation: 6963

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

Upvotes: 2

Desdenova
Desdenova

Reputation: 5378

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

Upvotes: 0

Related Questions