简体   繁体   中英

Overwrite ios back button

I have an app that displays a webView of a web page. The web consists of a main page with a lot of subpages. When I am on the main page I want the navigation Back button to to keep the default behaviour of going back to the previous view controller. But when the web is on a subpage I would like the navigation Back button to take the web to the main web page.

So I need to catch when the user presses the back button and if he is on a web subpage take him to the web main page and prevent the webView from closing. I was thinking that I can catch the back button using viewWillDisappear(), but how can I prevent the view from closing?

Check this post out:

Execute action when back bar button of UINavigationController is pressed

Something like this ought to do, in your view controller code:

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.hidesBackButton = true
    let customBackButtonItem = UIBarButtonItem(title: "Back", style: .Bordered, target: self, action:#selector(customBackMethod(_:)))
    self.navigationItem.leftBarButtonItem = customBackButtonItem
}

// @objc is so we can use #selector() up above
@objc func customBackMethod(sender: UIBarButtonItem) {
    if webView.canGoBack {
        webView.goBack()
    }
}

Note that you may have to use UIBarButtonItem(image:, style:, target:, action:) if you want a 'back' image, or UIBarButtonItem(customView:). See this question and answer for more details: https://stackoverflow.com/a/36180934/892990

Similar to KickimusButticus' answer:

If you want to more easily do it using the storyboard and such, you could hook up your back button to an IBAction like so:

@IBAction func back() {

}

And have internal testing for whether or not the user is in a sub-page of the webview. If they are, you can mess with the webview. If they are on the home page, you could simply use the back button to segue to your main view controller or use the self.dismissViewControllerAnimated(true, completion: nil) to dismiss that view controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM