Search code examples
iosobjective-cbuttonuinavigationbar

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?


Solution

  • 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