Custom UIButton as Navigation Item Back Button working, but does not show

460 Views Asked by At
    let btnName = UIButton()
    btnName.setImage(UIImage(named: "backIcon"), for: .normal)
    btnName.addTarget(self, action: #selector(AddContactViewController.backAction), for: .touchUpInside)
    let leftBarButton = UIBarButtonItem()
    leftBarButton.customView = btnName
    self.navigationItem.leftBarButtonItem = leftBarButton

It works fine, it does what is intended to do. However, on the navigation item it's invisible. But when I click on the area where it should be. It works.

3

There are 3 best solutions below

0
On

Everything is ok, except you forgot to set the frame for your button, that's why it's not being shown.

let btnName = UIButton(frame: CGRect(x: 0, y: 0, width: 18, height: 17))
btnName.setImage(UIImage(named: "backIcon"), for: .normal)
btnName.addTarget(self, action: #selector(AddContactViewController.backAction), for: .touchUpInside)

let leftBarButton = UIBarButtonItem()
leftBarButton.customView = btnName

self.navigationItem.leftBarButtonItem = leftBarButton
0
On

Actually you may have two navigation bars one is of your current class and another is of your previous class.So, you can try by adding below code in your previous class.

override func viewWillDisappear(_ animated: Bool) {
        self.navigationController!.navigationBar.isHidden = true
}

I also faced the same problem and it worked for me. May be it will help you.

0
On

Rather than hard-coding some frame values, you are better off calling the sizeToFit() method after setting the image, title, etc. I hit this problem today where a custom back button was showing OK on iOS11, but was not visible on iOS9.

btnName.sizeToFit()