Swift - UIWebview back button with NavigationBar Back Button

23,292

Solution 1

Adding to your code you could add an else which would run when there is no more web history and pop the view controller, which would go back to the previous view controller (if you have you view controllers in a navigation controller):

if(webview.canGoBack) {
    //Go back in webview history
    webview.goBack()
} else {
    //Pop view controller to preview view controller
    self.navigationController?.popViewControllerAnimated(true)
}

Also, if you want to remove the default back button and use your custom button add this code in ViewDidLoad:

self.navigationItem.backBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.Plain, target: self, action:  "onBackButton_Clicked:")

And change your method above from:

onBackButton_Clicked(sender: UIButton)

to:

onBackButton_Clicked(sender: UIBarButtonItem)

Solution 2

I would suggest to overload the back button function and check for history.

override func viewDidLoad {
        super.viewDidLoad()
        self.navigationItem.hidesBackButton = true
        let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Bordered, target: self, action: "back:")
        self.navigationItem.leftBarButtonItem = newBackButton;
    }

    func back(sender: UIBarButtonItem) {
        if(webview.canGoBack) {
             webview.goBack()
        } else {
             self.navigationController.popViewController(animated:true)
        }
    }
Share:
23,292
ADuggan
Author by

ADuggan

Updated on April 01, 2020

Comments

  • ADuggan
    ADuggan about 4 years

    At the moment im using a button on my uiwebview to go back through each webpage that the user searches and its working great. But is there anyway to use the navigation bar back button to go back through previous webpages and when theres no more pages to go back to then open the previous view controller?

    Heres the code im using to go back which is just connected to a UIButton.

    // Back button events
    func onBackButton_Clicked(sender: UIButton)
    {
        if(webview.canGoBack)
        {
            webview.goBack()
        }
    }
    

    Any help would be great.

  • ADuggan
    ADuggan about 8 years
    That helped but I had to change it to self.navigationController?.popViewControllerAnimated(true)
  • Joe Benton
    Joe Benton about 8 years
    Updated the answer ;) Hope that helped
  • RajV
    RajV over 7 years
    backBarButtonItem may not be appropriate here. Instead use a custom leftBarButtonItem as mentioned by Maxime Vantillard below. The back button in iOS is actually defined for the controller immediately below the topmost controller.