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
This is the simplest and easiest solution in Swift, just copy/paste and fill in the blanks:
let navTapGesture = UITapGestureRecognizer(target: <#T##AnyObject?#>, action: <#T##Selector#>)
navigationItem.titleView.userInteractionEnabled = true
navigationItem.titleView.addGestureRecognizer(navTapGesture)
Be sure to set the userInteractionEnabled
to true
on the titleView
, its off by default.
One of the possible options: (Use UILabel)
UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doSomething:)];
UILabel * titleView = [UILabel new];
titleView.text = @"Test";
[titleView sizeToFit];
titleView.userInteractionEnabled = YES;
[titleView addGestureRecognizer:tapGesture];
self.navigationItem.titleView = titleView;
The solution I found is a button, I use the following (but I don't know how "legal" it is):
UIButton *titleLabelButton = [UIButton buttonWithType:UIButtonTypeCustom];
[titleLabelButton setTitle:@"myTitle" forState:UIControlStateNormal];
titleLabelButton.frame = CGRectMake(0, 0, 70, 44);
titleLabelButton.font = [UIFont boldSystemFontOfSize:16];
[titleLabelButton addTarget:self action:@selector(didTapTitleView:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.titleView = titleLabelButton;
Put that bit of code where ever you set your title. Then elsewhere I had this to test:
- (IBAction)didTapTitleView:(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.
I didn't want to specify a button as a custom titleView
because that would mean I can't use the standard title anymore. On the other hand, when adding a tap gesture recognizer to the navigation bar, we have to make sure that it doesn't fire when tapping a bar button.
This solution accomplishes both (to be added to a UINavigationBar
subclass):
- (void)awakeFromNib {
// put in -initWithFrame: if initialized manually
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ft_titleTapped:)];
[self addGestureRecognizer:tap];
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
UIView *titleView = [self valueForKey:@"titleView"];
CGRect titleFrame = titleView.frame;
titleFrame.origin.y = 0; // expand to full height of navBar
titleFrame.size.height = self.frame.size.height;
return CGRectContainsPoint(titleFrame, [gestureRecognizer locationInView:self]);
}
- (void)ft_titleTapped:(UITapGestureRecognizer*)sender {
if (sender.state == UIGestureRecognizerStateEnded) {
// could add some checks here that the delegate is indeed a navigation controller
UIViewController<FTViewControllerAdditions> *viewController = (id)[((UINavigationController*)self.delegate) topViewController];
if ([viewController respondsToSelector:@selector(titleViewTapped:)]) {
[viewController titleViewTapped:self];
}
}
}
It automatically sends a -titleViewTapped:
message to the view controller (if implemented). In a UITableViewController
subclass you could implement the method like this for a scroll to top feature:
- (void)titleViewTapped:(id)sender {
[self.tableView setContentOffset:CGPointMake(0, -self.tableView.contentInset.top) animated:YES];
}
Caution: we're retrieving the title view using the undocumented -valueForKey:@"titleView"
. It's technically not using a private API but might still fail in a future iOS version!
This can be done by attaching a UITapGestureRecognizer
to the navigation bar subview that corresponds to the titleView.
As the titleView's index varies depending on how many bar button items there are, it is necessary to iterate through all the navigation bar subviews to find the correct view.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
addTitleViewTapAction("tapped", numberOfTapsRequired: 3)
}
func addTitleViewTapAction(action: Selector, numberOfTapsRequired: Int) {
if let subviews = self.navigationController?.navigationBar.subviews {
for subview in subviews {
// the label title is a subview of UINavigationItemView
if let _ = subview.subviews.first as? UILabel {
let gesture = UITapGestureRecognizer(target: self, action: action)
gesture.numberOfTapsRequired = numberOfTapsRequired
subview.userInteractionEnabled = true
subview.addGestureRecognizer(gesture)
break
}
}
}
}
@objc func tapped() {
print("secret tap")
}
}
You can add a gesture recognizer to be a single tap to the title of the navigation controller. I found that in the navigationBar subviews, the title is the one at index 1, the left button's index is 0 and the right button's index is 2.
UITapGestureRecognizer *navSingleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(navSingleTap)];
navSingleTap.numberOfTapsRequired = 1;
[[self.navigationController.navigationBar.subviews objectAtIndex:1] setUserInteractionEnabled:YES];
[[self.navigationController.navigationBar.subviews objectAtIndex:1] addGestureRecognizer:navSingleTap];
and then implement the following somewhere in your implementation.
-(void)navSingleTap
So you can use this for a single tap, or you can implement any gesture recognizer you want on that title.