crperez
crperez

Reputation: 127

Setting an image as Navigation Bar title

I'm trying to set an image as the title of a navigation bar in swift using the code below. The code builds successfully, but the image does not display. Any advice would be appreciated.

import UIKit

class FirstViewController: UIViewController { 

    @IBOutlet weak var navigationBar: UINavigationItem!
    var convoImage: UIImage!
    var convoImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.convoImage = UIImage(contentsOfFile: "conversation.png")
        self.convoImageView = UIImageView(image: self.convoImage)
        self.navigationBar.titleView = self.convoImageView
    }
}

Upvotes: 2

Views: 2610

Answers (2)

Girish Chovatiya
Girish Chovatiya

Reputation: 195

Set the navigationItem's titleView.

let image = UIImage(named: "image_name.png")
self.navigationItem.titleView = UIImageView(image: image)

In your code replace below line:

self.convoImage = UIImage(contentsOfFile: "conversation.png")

with

self.convoImage = UIImage(named: "conversation.png")

Upvotes: 1

Anupam Mishra
Anupam Mishra

Reputation: 3588

You should set convoImageView frame .

import UIKit

class FirstViewController: UIViewController { 

    @IBOutlet weak var navigationBar: UINavigationItem!
    var convoImage: UIImage!
    var convoImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.convoImage = UIImage(named: "conversation.png")
        self.convoImageView = UIImageView(image: self.convoImage)
        self.convoImageView.frame = CGRectMake(0,0,720,100)
        self.navigationBar.titleView = self.convoImageView
    }
}

Upvotes: 0

Related Questions