-2

I added a label and an image to the navigation item title view, like this - https://stackoverflow.com/a/38548905/1373592

And I added these three lines of code, to make the title clickable.

    ....
    let recognizer = UITapGestureRecognizer(target: self, action: #selector(MyViewController.titleTapped(_:)))
    navView.isUserInteractionEnabled = true
    navView.addGestureRecognizer(recognizer)

And this titleTapped function.

    @objc func titleTapped(_ tapGestureRecognizer: UITapGestureRecognizer) {
        print("Tapped")
    }

What am I doing wrong?

I tried adding gesture recognizer to the label, and to the image (separately). That didn't work either.

Thanks.

Shivam Tripathi
  • 1,405
  • 3
  • 19
  • 37
SKT
  • 271
  • 4
  • 15
  • Have you set `userInteractionEnabled` on the label? – Ollie Mar 13 '18 at 12:58
  • Your `NavView` has no frame... If you give it a background color, you'll see that it doesn't show up. If you set `navView.clipsToBounds = true`, you won't see your label or image. You need to give `NavView` a frame, and set the size and positions of label and image relative to that frame. – DonMag Mar 13 '18 at 13:05

2 Answers2

1

Your NavView has no frame, so there is nothing "there" to tap.

Add this line:

    // Create a navView to add to the navigation bar
    let navView = UIView()

    // new line
    navView.frame = CGRect(x: 0, y: 0, width: 200, height: 40)

    // Create the label
    let label = UILabel()

and you should be on your way.

DonMag
  • 69,424
  • 5
  • 50
  • 86
-1

100% sure working in my app and well tested.

 var tapGesture = UITapGestureRecognizer()

take your view and set IBOutlet like:

@IBOutlet weak var viewTap: UIView!     

Write pretty code on viewDidLoad() like:

tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.myviewTapped(_:)))
tapGesture.numberOfTapsRequired = 1
tapGesture.numberOfTouchesRequired = 1
viewTap.addGestureRecognizer(tapGesture)
viewTap.isUserInteractionEnabled = true

this method is calling when tap gesture recognized

 @objc func myviewTapped(_ sender: UITapGestureRecognizer) {

if self.viewTap.backgroundColor == UIColor.yellow {
    self.viewTap.backgroundColor = UIColor.green
}else{
    self.viewTap.backgroundColor = UIColor.yellow
}
}

Note: In your case you have to sure for view which view infront like UILabel or UIView that is nav and then assign the gesture to it.If your label cover the whole view then let's try to give gesture to label only.

Mr.Javed Multani
  • 12,549
  • 4
  • 53
  • 52
  • The OP is using the view as the `.titleView` in a NavigationBar... your answer doesn't address that at all. – DonMag Mar 13 '18 at 13:06