UINavigationBar Touch

前端 未结 9 1275
北恋
北恋 2020-12-23 17:53

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

9条回答
  •  一生所求
    2020-12-23 18:09

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

提交回复
热议问题