为什么我的 UITapGestureRecognizer 方法不在 swift 中调用 Navigationbar titleView

Why My UITapGestureRecognizer method not calling for Navigationbar titleView in swift

使用下面的代码我可以在导航栏中获取标题图片但是 titlePressed 方法没有调用..如果我点击标题我无法进入 HomeVC..请帮忙..在哪里我错了吗

func setUpNavigationBar(){

    let logoImageView = UIImageView.init(image: #imageLiteral(resourceName: "pic-logo"))
    logoImageView.tintColor = .darkGray
    logoImageView.frame = CGRect(x:0.0,y:0.0, width:100,height:25.0)
    logoImageView.contentMode = .scaleAspectFit
    logoImageView.widthAnchor.constraint(equalToConstant: 200).isActive = true
    logoImageView.heightAnchor.constraint(equalToConstant: 50).isActive = true
    self.navigationItem.titleView?.isUserInteractionEnabled = true
    let titleTap = UITapGestureRecognizer(target: self, action: #selector(titlePressed))
    self.navigationItem.titleView?.addGestureRecognizer(titleTap)
    self.navigationItem.titleView = logoImageView

}
@objc func titlePressed(){
    print("title clicked...")
    
    let vc = StoryBoard.main.instantiateViewController(identifier: "HomeVC") as! HomeVC
   
    self.navigationController?.pushViewController(vc, animated: true)
    
    
}
self.navigationItem.titleView?.addGestureRecognizer(titleTap)
self.navigationItem.titleView = logoImageView

你添加一个手势识别器,如果标题视图不为零,然后在下一行你立即将标题视图更改为完全不同的东西,它上面不会有手势识别器。

self.navigationItem.titleView = logoImageView
logoImageView.addGestureRecognizer(titleTap)

这一行:

self.navigationItem.titleView?.isUserInteractionEnabled = true

也是有问题的,因为:此时 titleView 可能为 nil,因此这一行将不执行任何操作,无论如何您稍后都会更改标题视图。