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