Henrik Petterson Henrik Petterson - 6 months ago 92
Swift Question

UIBarButtonItem, add a back button using Swift

I want to add a back button to my webview app.

Looking through

UIBarButtonItem
, I can't seem to find a back button. See code:

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

let url = NSURL(string: "http://google.com")!
webView.loadRequest(NSURLRequest(URL: url))
webView.allowsBackForwardNavigationGestures = true

let refresh = UIBarButtonItem(barButtonSystemItem: .Refresh, target: webView, action: #selector(webView.reload))

let back = UIBarButtonItem(barButtonSystemItem: .Back, target: webView, action: #selector(webView.goBack))

toolbarItems = [back, refresh]
navigationController?.toolbarHidden = false

}


How do I add a back button to the toolbar?

Answer

I think you are forget too add UIBarbuttonItem in navigationItem

so you need to do code like:

self.navigationItem.rightBarButtonItems = toolbarItems // that show two right side button. 

if you want to show back button at left side and refresh button at right side in navigationbar then you must be code like:

 self.navigationItem.rightBarButtonItem = refresh
 self.navigationItem.leftBarButtonItem = back

That will be appear in you nevigation back button left side and refresh button right side

So your code something look like following:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let url = NSURL(string: "http://google.com")!
    webView.loadRequest(NSURLRequest(URL: url))
    webView.allowsBackForwardNavigationGestures = true

    let refresh = UIBarButtonItem(barButtonSystemItem: .Refresh, target: webView, action: #selector(webView.reload))

    //let back = UIBarButtonItem(barButtonSystemItem: .Back, target: webView, action: #selector(webView.goBack))

    let back = UIBarButtonItem(title: "Back",style: .Plain,target: webView,action: #selector(webView!.goBack))

   self.navigationItem.rightBarButtonItem = refresh
     self.navigationItem.leftBarButtonItem = back
    navigationController?.toolbarHidden = false

}

if you want to add multiple button at leftbarbutton then create one more UIBarbuttonItem object something like:

let undo = UIBarButtonItem(barButtonSystemItem: .Undo, target: webView, action: #selector(webView.undo))

self.navigationItem.leftBarButtonItems = [back,undo]

that will be display two left button on navigation bar

Comments