Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - UIWebview back button with NavigationBar Back Button

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.

like image 790
ADuggan Avatar asked Apr 01 '16 08:04

ADuggan


1 Answers

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)
like image 121
Joe Benton Avatar answered Oct 21 '22 15:10

Joe Benton