18
votes

I'm a swift newbie and made a demo app which has a UIViewController and UITableViewController in the Storyboard. The UIViewController has a Collection View and an embedded navigation controller. On tapping a collection view cell, the app segues to the UITableViewController. I can come back to my UIViewController from the UITableViewController as well. All this works well. Now, some of the rows in my UITableViewController have URLs. On tapping a URL, I programmatically create a webview inside a UIviewcontroller and get the URL to load in it. The issue is that I can't dismiss the webview and get back to my UITableViewController after this. This is the code I have in my UITableViewController class :

// When user taps a row, get the URL and load it in a webview
let mywebViewController = UIViewController()
let webView = UIWebView(frame: mywebViewController.view.bounds)
webView.loadRequest(NSURLRequest(URL: url)) // url from the row a user taps
mywebViewController.view = webView
self.navigationController!.presentViewController(mywebViewController, animated: true, completion: nil)

How can I add a Done button to this programmatically created UIviewcontroller to dismiss the webview and get back to my UITableViewController

5

5 Answers

37
votes

You can wrap the mywebViewController in a UINavigationController then set the rightBarButtonItem to UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismiss") like this:

let navController = UINavigationController(rootViewController: mywebViewController)
mywebViewController.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismiss")

self.navigationController!.presentViewController(navController, animated: true, completion: nil)

and add a dismiss function in your UITableViewController:

func dismiss() {
    self.dismissViewControllerAnimated(true, completion: nil)
}
0
votes

Add done button to your presented ViewController and make an action for it. To dismiss ViewController try this :

self.dismissViewControllerAnimated(true, completion: nil)
0
votes

You can do one thing.

As you are pushing your mywebViewController into the navigation controller, make the navigation bar visible.

By simply tapping on Back button in the navigation bar you can easily dismiss your mywebViewController.

Hope this helps you. :)

0
votes

Add button in mywebViewController and in its @IBAction, call

self.dismissViewControllerAnimated(true, completion: nil)
-1
votes

Update for Swift 4 & 5

In the VC you're navigating from

navController.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.dismiss))

Have to declare your selector as an @objc func

@objc func dismiss(){
        self.dismiss(animated: true)
    }