learn_swift
learn_swift

Reputation: 83

Why My UITapGestureRecognizer method not calling for Navigationbar titleView in swift

with the below code i am able to get title image in navigationbar but the titlePressed method is not calling.. and if i tap title i am unable to go HomeVC.. please do help.. where am i wrong

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

Upvotes: 0

Views: 180

Answers (1)

Shadowrun
Shadowrun

Reputation: 3867

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

You add a gesture recognizer, if title view is not nil, and then on the next line you change the title view right away to a different thing altogether, which won't have a gesture recognizer on it.

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

This line:

self.navigationItem.titleView?.isUserInteractionEnabled = true

Is also problematic because: titleView is likely nil at this point, so this line will do nothing, and you change the title view later anyway.

Upvotes: 1

Related Questions