Burgan
Burgan

Reputation: 900

How to show a UIWebView after UITableViewCell is selected?

I currently have my root view controller as a TableViewController with a NavigationController.

window?.rootViewController = UINavigationController(rootViewController: FeedTableViewController(style: .grouped))

When a cell is selected, in my TableViewController, I would like to load a WebView with a string of HTML.

My code is currently:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let layout = TableViewLayout(indexPath: indexPath) else { fatalError() }
        switch layout {
        case .items:
            // load web view with html from a string
        default:
            break
        }
    }

I have seen how to load a string of HTML into a WebView, but I don't know how to make that WebView the view that is shown when a cell is selected. I also need this to not break the NavigationController if possible.

Upvotes: 0

Views: 254

Answers (1)

GIJOW
GIJOW

Reputation: 2353

Quite hard by your comments to know "if that preserves NavigationController".

But I think it can at least give you a clue:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let layout = TableViewLayout(indexPath: indexPath) else { fatalError() }
        switch layout {
        case .items:
             let webView = UIWebView(frame: CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y, width: tableView.frame.size.width, height: tableView.frame.size.height)
             let testHTML = Bundle.main.path(forResource: "privacy", ofType: "html")
             do {
                 let contents = try NSString(contentsOfFile: testHTML!, encoding: String.Encoding.utf8.rawValue)
                 let baseUrl = NSURL(fileURLWithPath: testHTML!) //for load css file
                 webView.loadHTMLString(contents as String, baseURL: baseUrl as URL)
             } catch {
                print("error")
             }
             self.view.addSubview(webView)
        default:
            break
        }
}

It will add a webView in same frame as your table view.

Don't forget to set up your html origin:

let testHTML = Bundle.main.path(forResource: "privacy", ofType: "html")

Upvotes: 1

Related Questions