I am currently using SWRevealViewController for a sidebar menu in my app. When I click one of the options, the destination view controller doesn't have a 'back' button because it hasn't come from a proper view controller (i.e. page to go back to).
Therefore I am wanting to manually create a back button on the destination view controller which will go back to the home view controller.
I have looked at the code here: How do I manually set the "Back" destination in iOS apps
But I am struggling to implement this in Swift (one error after another!). Any help? Thanks!
EDIT
I have tried the suggestion below, but the back button just doesn't appear. This may have something to with the fact I have the navbar hidden in other views and do the following on the destination view:
override func viewDidLoad() {
super.viewDidLoad()
navigationController.setNavigationBarHidden(false, animated:true)
var myBackButton:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
myBackButton.addTarget(self, action: "popToRoot:", forControlEvents: UIControlEvents.TouchUpInside)
var myCustomBackButtonItem:UIBarButtonItem = UIBarButtonItem(customView: myBackButton)
self.navigationItem.leftBarButtonItem = myCustomBackButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func popToRoot(sender:UIBarButtonItem){
self.navigationController.popToRootViewControllerAnimated(true)
}
Not sure why the back button won't show up?
Edit
This is the prepareForSegue from my sidebar view controller. If there is a way to check for the segue identifier 'test' then I can set the back button from here?
- (void) prepareForSegue: (UIStoryboardSegue *) segue sender: (id) sender
{
// Set the title of navigation bar by using the menu items
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
UINavigationController *destViewController = (UINavigationController*)segue.destinationViewController;
destViewController.title = [[_menuItems objectAtIndex:indexPath.row] capitalizedString];
if ( [segue isKindOfClass: [SWRevealViewControllerSegue class]] ) {
SWRevealViewControllerSegue *swSegue = (SWRevealViewControllerSegue*) segue;
swSegue.performBlock = ^(SWRevealViewControllerSegue* rvc_segue, UIViewController* svc, UIViewController* dvc) {
UINavigationController* navController = (UINavigationController*)self.revealViewController.frontViewController;
[navController setViewControllers: @[dvc] animated: NO ];
[self.revealViewController setFrontViewPosition: FrontViewPositionLeft animated: YES];
};
}
}
Swift 3.0 Solution:
In Swift 2.1
In AppDelegate I have
In ViewController I update Navigation Items in viewWillAppear method this way
Here's an updated version for Swift 2/2.1:
You can write that in swift like this
Write this to add button on
navigationController
this will pops to
rootViewController