James Lingo James Lingo - 5 months ago 16
Swift Question

Trying to set rightBarButton programmatically in Swift

After reading this question: How to set back button text in Swift,

I started moving the code I was using to configure the nav bar right button to the view controller that calls the xib I'm presenting (ParticipantEditorViewController) like so:

import UIKit

class ViewController: UIViewController {

/*
* This is placeholder class. The code below will need to be added to whichever view controllers summon the participant editor, in their prepareForSegue method.
*/

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
print("snap")

if let participantEditor = segue.destinationViewController as? ParticipantEditorViewController {
print("crackle")

let barButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Action, target: participantEditor, action: nil)
// let barButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Action, target: participantEditor, action: Selector(participantEditor.presentActionMenu()))
print("pop")

navigationItem.rightBarButtonItem = barButton
}
}
}


But I'm still not able to configure the nav bar programmatically. Any help on what I'm missing?

Answer

The prepareForSegue function will be called when you're segueing to another view controller. If you want to configure the navigation bar, do it in other function that will be called when the this view controller is going to be shown, for example viewDidLoad.