iOS - add image and text in title of Navigation bar

Darrell picture Darrell · Jul 24, 2016 · Viewed 15.6k times · Source

I would like to create a nav bar similar to what's in the image that's attached.

The title of the nav bar will be a combination of an image and text.

  1. Should this be done per any best practice?

  2. How can it be done?

Screen shot of mockup of nav bar with image and text

Answer

Lyndsey Scott picture Lyndsey Scott · Jul 24, 2016

As this answer shows, the easiest solution is to add the text to your image and add that image to the navigation bar like so:

var image = UIImage(named: "logo.png")
self.navigationItem.titleView = UIImageView(image: image)

But if you have to add text and an image separately (for example, in the case of localization), you can set your navigation bar's title view to contain both image and text by adding them to a UIView and setting the navigationItem's title view to that UIView, for example (assuming the navigation bar is part of a navigation controller):

// Only execute the code if there's a navigation controller 
if self.navigationController == nil {
    return
}

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

// Create the label
let label = UILabel()
label.text = "Text"
label.sizeToFit()
label.center = navView.center
label.textAlignment = NSTextAlignment.Center

// Create the image view
let image = UIImageView()
image.image = UIImage(named: "Image.png")
// To maintain the image's aspect ratio:
let imageAspect = image.image!.size.width/image.image!.size.height
// Setting the image frame so that it's immediately before the text:
image.frame = CGRect(x: label.frame.origin.x-label.frame.size.height*imageAspect, y: label.frame.origin.y, width: label.frame.size.height*imageAspect, height: label.frame.size.height)
image.contentMode = UIViewContentMode.ScaleAspectFit

// Add both the label and image view to the navView
navView.addSubview(label)
navView.addSubview(image)

// Set the navigation bar's navigation item's titleView to the navView
self.navigationItem.titleView = navView

// Set the navView's frame to fit within the titleView
navView.sizeToFit()