如何从表格中选择不同的网站?

时间:2017-06-06 15:52:11

标签: swift webview tableview

我正在使用Hacking With Swift的Project 4进行一些奖励挑战,我不知道如何从表格视图中选择不同的网站。我有一个表视图,可以看到带有Web视图的详细视图,但我不确定从这里开始。

我的视图控制器

import UIKit

class ViewController: UITableViewController {

var websites = ["apple.com", "hackingwithswift.com"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //THIS DISPLAYS THE WEBSITE NAMES IN THE TABLE ROWS
    return websites.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Website", for: indexPath)
    //THIS DISPLAYS A WEBSITE NAME IN EACH CELL
    cell.textLabel?.text = websites[indexPath.row]
    return cell
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
        vc.selectedWebsite = websites[indexPath.row]
        //THIS PIECE BELOW LOADS ANIMATES THE NEW VIEW CONTROLLER
        navigationController?.pushViewController(vc, animated: true)
    }
}

}

和我的详细视图控制器

import UIKit
import WebKit

class DetailViewController: UIViewController, WKNavigationDelegate {

var selectedWebsite: String?
var webView: WKWebView!

override func loadView() {
    webView = WKWebView()
    webView.navigationDelegate = self
    view = webView
}

override func viewDidLoad() {
    let url = URL(string: "https://www.hackingwithswift.com")!
    webView.load(URLRequest(url: url))
    webView.allowsBackForwardNavigationGestures = true
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

提前感谢任何想法。我对此很陌生,对于该怎么做感到无能为力。

1 个答案:

答案 0 :(得分:1)

将所选网址传递给DetailViewController URL中的viewDidLoad()

let url = URL(string: selectedWebsite!)!