views:

547

answers:

2

I would like to fire an event on touch when a user taps the title of the navigation bar of one of my views.

I'm at a bit of a loss on whether I can access the view of the title of the UINavigationBar in order to wire up a touch event to it.

Is this even possible?

+1  A: 

The UINavigationItem class reference has a titleView property, which you can set to your custom UIView.

In other words, make a subclass of UIView with your touch handlers, and then when you push your navigation item, set that item's titleView property to an instance of your subclass.

Alex Reynolds
Thanks, but then how do I act on that touch, for example - how can I call a method in my overall view controller if the titleView is touched?
mootymoots
Also, with this approach, my title attribute is lost. Could you explain further?I've added a touchesBegan handler with a simple NSLog(@"touched"); but it does nothing when the titleView is hit. I'm creating an instance of the subclass, and assigning it to the instance of the view I'm about to push, ie view.navigationItem.titleView = mySubclass;
mootymoots
Your custom `UIView` can have many properties, including a `UILabel` to replace the title, and a `UIViewController` property for the "parent" view controller, which you set when you create an instance of your custom view. Also check that your view has a frame of sufficient size.
Alex Reynolds
+3  A: 

I've been thinking about this myself, as I also want to detect a touch on the navigation bar title. I'm using a UITableViewController and tables don't seem to like touchesBegan.. Whilst sitting "reading the newspaper" (read, on the loo using my iPhone), I had an idea. Would it be possible to addTarget:action:forControlEvents on a label, then add that to the title view? I'm fairly new to the whole thing myself too.


Edit: ok, after trying the above, I found that it can't be done. Labels don't work with addTarget.. So instead I tried a button, and have gone with the following to test my theory (but I don't know how "legal" it is):

UIButton *titleLabel = [UIButton buttonWithType:UIButtonTypeCustom];
[titleLabel setTitle:@"myTitle" forState:UIControlStateNormal];
titleLabel.frame = CGRectMake(0, 0, 70, 44);
titleLabel.font = [UIFont boldSystemFontOfSize:16];
[titleLabel addTarget:self action:@selector(titleTap:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.titleView = titleLabel;

Put that bit of code where ever you set your title. Then elsewhere I had this to test:

- (IBAction) titleTap:(id) sender
{
    NSLog(@"Title tap");
}

which logged "Title tap" on the console!

The way I've gone about this may be completely wrong, but might give you an idea on what you can look in to. It's certainly helped me out! There's probably a better way of doing it though.

Ryan Moores