Search code examples
iosswiftuinavigationitem

navigationItem.setLeftBarButton() not working on old versions


I am using pushViewController like the following code:

let vc = A()   
self.navigationController?.pushViewController(vc, animated:true)

I want to add a navigationItem to the page that opens. This code working on new versions but not working on iPhone 5(iOS 9.3) Simulator and iPad(10.3.3)

class A: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        configureNavigationItem()
    }

    func configureNavigationItem() {
        let buttonLogo = UIButton(type: .custom)
        buttonLogo.setImage(UIImage(named: "logo"), for: .normal)
        buttonLogo.setTitle("", for: .normal)
        buttonLogo.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -9, right: 0)
        let itemLogo = UIBarButtonItem(customView: buttonLogo)
        self.navigationItem.setLeftBarButton(itemLogo, animated: true)
    }

}

Nothing appears in old versions. How can I solve this?


Solution

  • The problem is that your UIButton has zero size. You need to give it a size!

    buttonLogo.sizeToFit()
    let itemLogo = UIBarButtonItem(customView: buttonLogo)
    

    The reason your code works in iOS 11 is that it uses autolayout to size the button as a customView. But that is a new feature of iOS 11.