Nan
Nan

Reputation: 524

About leftBarButtonItem doesn't appear programmatically

I am trying to add a leftBarButtonItem in my View Controller's navigation bar programmatically (This View Controller is embedded in a Navigation Controller). I implement this code in viewDidLoad

let backButton = UIButton(type: .custom)
backButton.setImage(UIImage(named: "BackButton.png"), for: .normal)
backButton.setTitle("Back", for: .normal)
backButton.setTitleColor(backButton.tintColor, for: .normal)
backButton.addTarget(self, action: #selector(self.backAction(_:)), for: .touchUpInside)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)

I run the test, but the backButton does not appear in the view controller at all. I am thinking, Should I put this piece code in the navigation controller with the View Controller is embedded in? How to resolve this issue?

Upvotes: 0

Views: 258

Answers (1)

Priyam Dutta
Priyam Dutta

Reputation: 702

Use the following code:

self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "Back")!, style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.actionBack))

Upvotes: 1

Related Questions