0

I have two viewControllers.

vc1 -> presentVC -> vc2

vc2 inherit UINavigationController

I want to set title & backButton in vc2,but it doesn't work.

class vc2: UINavigationController {

override func viewDidLoad() {
    super.viewDidLoad()

    // set title!!!
    //self.navigationItem.title = "123"
    //self.navigationController?.navigationBar.topItem?.title = "123"
    //self.title = "123"
    //self.navigationBar.topItem?.title = "123"
    //self.navigationItem.title = "123"

    // set backButton!!!
    let navButtonWidth:CGFloat = 44
    let backButton:UIButton = UIButton()
    backButton.setImage(backImage, for: .normal)
    backButton.addTarget(self, action: #selector(back), for: .touchUpInside)
    self.navigationItem.leftBarButtonItems = [UIBarButtonItem(customView: backButton)]

}
  • What does not work button not adding on navigation bar or not performing action? – Tushar Sharma Mar 06 '17 at 07:27
  • how to make it work? –  Mar 06 '17 at 07:30
  • You want to go on previous controller on button click? – Tushar Sharma Mar 06 '17 at 07:32
  • CHECK THIS-: http://stackoverflow.com/questions/40230261/jsqmessageview-controller-add-back-button-image-on-navigation-bar-swift – Tushar Sharma Mar 06 '17 at 07:36
  • Check [this](http://stackoverflow.com/questions/6154237/how-to-set-the-title-of-a-navigation-bar-programatically) (title) & [this](http://stackoverflow.com/questions/40230261/jsqmessageview-controller-add-back-button-image-on-navigation-bar-swift) (back button) out. Good luck. – vbuzze Mar 06 '17 at 07:36

2 Answers2

1

Place the code below in perform(segue) or viewWillDissappear depended on how do you do your presentation - via Storyboard segue or manually from code.

let backButton = UIBarButtonItem()
backButton.title = "whatever_you_want"
navigationItem.backBarButtonItem = backButton

And in viewDidLoad of your vc2 simply put

navigationItem.title = "Controller title"
SwiftStudier
  • 2,272
  • 5
  • 21
  • 43
0

I can change it in storyboard Or change it in code.

I usually do this.

First hide navigation bar from default navigation controller.

navigationController?.navigationBar.hidden = true

Create navigation bar in storyboard and outlet it.

 @IBOutlet weak var navigationBar: UINavigationBar!

Create custom navigation item.

private lazy var customNavigationItem: UINavigationItem = {
    let navigationItem = UINavigationItem()
    let backButton = UIBarButtonItem(image: UIImage(named: "cancel_icon"), style: .Plain, target: self, action: #selector(cancelTapped))

    navigationItem.leftBarButtonItem = backButton
    navigationItem.title = "Your Title"

    return navigationItem
}()

Add custom navigation item to navigation bar

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    navigationController?.navigationBar.hidden = true
    navigationBar.setItems([customNavigationItem], animated: false)
}

Hope it help.

Luan Tran
  • 1,142
  • 7
  • 15