Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a "Done" button to dismiss a programmatically created UIViewController

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

like image 919
smokinguns Avatar asked Sep 02 '15 06:09

smokinguns


1 Answers

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)
}
like image 92
Bannings Avatar answered Oct 20 '22 10:10

Bannings