Deuce bigalow Deuce bigalow - 4 months ago 23
iOS Question

Back button position on navigation controller

I'm currently trying to develop a custom search for an iOS app.

I have managed to get the search controller appearing and the search bar appearing properly, although my only problem is that I need the back button to appear on the right of the navigation bar rather than the left, see below

(As you can see the back button is on the left but I need it to be on the right)
http://imgur.com/qLPoIfG

Here is my code:

import UIKit


class SearchTop10Controller: UITableViewController, UISearchResultsUpdating {

override func viewDidLoad() {
super.viewDidLoad()

let searchController = UISearchController(searchResultsController: self);

self.definesPresentationContext = true;
searchController.searchResultsUpdater = self;
// searchController.hidesNavigationBarDuringPresentation = true;

searchController.dimsBackgroundDuringPresentation = false;
searchController.searchBar.sizeToFit();
self.navigationItem.titleView = searchController.searchBar;
self.tableView.tableHeaderView = searchController.searchBar;
}

override func viewDidAppear(animated: Bool) {


}

func updateSearchResultsForSearchController(searchController: UISearchController) {
//do whatever with searchController here.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

Answer

You can add a back button to the right bar item like this:

let backButton : UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style: UIBarButtonItemStyle.Plain, target: self, action: #selector(back))
self.navigationItem.rightBarButtonItem = backButton

Where back_icon is an image that you are using and back is the following function:

func back() {
    self.navigationController?.popViewControllerAnimated(true)
}

To hide the left bar item:

self.navigationItem.leftBarButtonItem = nil

or:

self.navigationItem.hidesBackButton = true
Comments