'Set navigation item from UINavigationController extension
I wrote a function to show my app logo in the middle of the navigation bar, and it is working fine when I call it from viewDidLoad() function.
But, when I tried to add it to a UINavigationController extension, it is not working! Although the function is called, the logo does not appear.
Any idea?
Thanks
extension UINavigationController {
func showNavLogo(){
let imageW = 59
let imageH = 30
let imageView = UIImageView()
imageView.image = UIImage(named: "Logo.png")
imageView.contentMode = .scaleAspectFit
self.navigationItem.titleView = imageView
let currWidth = self.navigationItem.titleView?.widthAnchor.constraint(equalToConstant: CGFloat(imageW))
currWidth?.isActive = true
let currHeight = self.navigationItem.titleView?.heightAnchor.constraint(equalToConstant: CGFloat(imageH))
currHeight?.isActive = true
}
}
Solution 1:[1]
I found the solution by adding the function to UIViewController extension instead of UINavigationController
extension UIViewController {
func showNavLogo(){
let imageW = 59
let imageH = 30
let imageView = UIImageView()
imageView.image = UIImage(named: "Logo.png")
imageView.contentMode = .scaleAspectFit
self.navigationItem.titleView = imageView
let currWidth = self.navigationItem.titleView?.widthAnchor.constraint(equalToConstant: CGFloat(imageW))
currWidth?.isActive = true
let currHeight = self.navigationItem.titleView?.heightAnchor.constraint(equalToConstant: CGFloat(imageH))
currHeight?.isActive = true
}
Solution 2:[2]
Did you remember to call self.showNavLogo() in your viewDidload?
your extension means you have a function called showNavlogo, but you may still have to call the showlogo method by using the self..showNavLogo() in your viewDidload or viewWillAppear.
Also ensure your storyboard or View controller or nib is mapped to a Navigation controller for your viewcontroller to implement your method.
Solution 3:[3]
changing the extension to UIViewcontroller worked for me
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zuhair Ali |
| Solution 2 | |
| Solution 3 | abike babatunde |
