swiftEnthusiast
swiftEnthusiast

Reputation: 15

Clickable Image as Nav Bar Title in Swift

I've looked through several threads on here that discuss:

  1. Setting an image for title
  2. Using a button for title

However, I'm trying to combine the two, i.e., clickable image (button) as title.

Unfortunately, while the below code compiles the image doesn't show when assigned as a button. Any suggestions?

func addNavBarImage() {
    let navController = navigationController!

    let button =  UIButton(type: .custom)
    var image = UIImage(named: "textLogo")
    image = image?.withRenderingMode(.alwaysOriginal)

    let bannerWidth = navController.navigationBar.frame.size.width
    let bannerHeight = navController.navigationBar.frame.size.height

    let bannerX = bannerWidth / 2 - image!.size.width  / 2
    let bannerY = bannerHeight / 2 - image!.size.height / 2

    button.frame = CGRect(x: bannerX, y: bannerY, width: bannerWidth, height: bannerHeight)
    button.imageView?.contentMode = .scaleAspectFit
    button.imageView?.image = image

    button.addTarget(self, action: #selector(self.logoTapped), for: .touchUpInside)
    self.navigationItem.titleView = button
}

Upvotes: 0

Views: 353

Answers (2)

Taimoor Suleman
Taimoor Suleman

Reputation: 1616

Working code for me.

let button =  UIButton(type: .custom)
button.setImage(UIImage (named: "your_image"), for: .normal)
button.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
button.backgroundColor = UIColor.clear
button.setTitle("Button", for: .normal)
button.addTarget(self, action: #selector(self.clickOnButton), for: .touchUpInside)
self.navigationItem.titleView = button

Here you can see in last line button is directly set to the titleView of navigationItem which will add button at the center of navigation bar.

Action method for button is below:

@objc func clickOnButton(button: UIButton) {
    print("Title Tapped")
}

Upvotes: 0

Bliss
Bliss

Reputation: 575

create UIImageView, add it as titleView and add UITapGestureRecognizer to your UIImageView

let imageView = UIImageView()
imageView.image = UIImage.named("yourImage")
// do any settings to your imageView
let titleTap = UITapGestureRecognizer(target: self, action: #selector(titlePressed))
self.navigationItem.titleView = imageView
self.navigationItem.titleView?.isUserInteractionEnabled = true
self.navigationItem.titleView?.addGestureRecognizer(titleTap)

Upvotes: 2

Related Questions