Reputation: 724
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?
Upvotes: 0
Views: 548
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
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