选择 UITableViewCell 后如何显示 UIWebView?

How to show a UIWebView after UITableViewCell is selected?

我目前的根视图控制器是带有 NavigationController 的 TableViewController。

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

选择一个单元格后,在我的 TableViewController 中,我想加载一个带有 HTML.

字符串的 WebView

我的代码目前是:

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
        }
    }

我已经看到如何将 HTML 的字符串加载到 WebView 中,但我不知道如何使该 WebView 成为选择单元格时显示的视图。如果可能的话,我还需要它不要破坏 NavigationController。

很难通过您的评论知道 "if that preserves NavigationController"。

不过我觉得至少可以给大家一个线索:

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
        }
}

它将在与您的 table 视图相同的框架中添加一个 webView。

不要忘记设置您的 html 来源:

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