0

I have a UITableViewController that is embedded into a NavigationController, see below:

enter image description here

And here is how I added in my image in the title:

navigationItem.titleView = UIImageView(image: Views.navigationBarLogo)

However, I have another UITableViewController create programmatically and of course the image in the navigation controller would disappear, is there a way to add in the image without repeating my code above.

Thanks!

Brendon Cheung
  • 995
  • 9
  • 29
  • see this once https://stackoverflow.com/questions/39739660/how-to-use-an-image-logo-on-the-navigation-bar-instead-of-title – Anbu.Karthik Aug 15 '17 at 01:56

1 Answers1

2

The UINavigationItem is specific to a single view controller. The only way to do what you want would be to create a base class that sets the titleView and then have each of the desired view controllers in your navigation controller inherit from your base class. Sample base class:

class MyBaseClass: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.navigationItem.titleView = UIImageView(image: Views.navigationBarLogo)
    }
}
bjd23
  • 276
  • 3
  • 8
  • Thanks, and from your answer, what I can visualize (since I don't have my mac with me at the moment) is go to my app delegate and instantiate my `MybaseClass` and a `navigationController` and set it's root controller be `MyBaseClass`. After that, all my other view controllers who needs the logo to show will need to inherit from `MyBaseClass`. correct? thanks!~ – Brendon Cheung Aug 15 '17 at 14:11
  • No need to instantiate your base class. Just make sure that any view controllers in your navigation controller hierarchy, that you want displaying your titleView, subclass your base class. For instance your class definition should start with something like this: class MyViewController: MyBaseClass – bjd23 Aug 15 '17 at 14:28
  • Hi there, sorry but I am still confused as to how to implement this correctly, can you please show my some code especially in the app delegate? thanks! – Brendon Cheung Aug 16 '17 at 01:02
  • I have no idea why you keep referencing the app delegate. You do not need to touch that. Take a look at this code: https://bitbucket.org/snippets/bdel23/695gdb. – bjd23 Aug 16 '17 at 02:43
  • MyTableViewController1 is embedded in a navigation controller in the storyboard. When a cell is tapped in MyTableViewController1, MyTableViewController2 is instantiated and pushed onto the navigation controller. Both table view controllers subclass MyBaseTableViewController which sets the titleView on the navigation controller. – bjd23 Aug 16 '17 at 02:48