通过TableViewCell加载网站时Swift可选错误

时间:2017-10-14 12:38:31

标签: swift xcode web view optional

我在下面附上了我的代码副本:

import WebKit
import UIKit

class WebsitesTableViewController: UITableViewController {
    var webview: WKWebView!
    var websites = ["apple.com", "hackingwithswift.com"]

    override func viewDidLoad() {
        super.viewDidLoad()

    }

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

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return websites.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "website", for: indexPath)

        cell.textLabel?.text = websites[indexPath.row]

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let vc = storyboard?.instantiateViewController(withIdentifier: "browser") as? ViewController {

            let url = URL(string: "https://" + websites[indexPath.row])
            webview.load(URLRequest(url: url!))
            webview.allowsBackForwardNavigationGestures = true
            navigationController?.pushViewController(vc, animated: true)
        }
    }


}

运行应用时,我似乎收到以下错误:

exc_bad_instruction(代码= EXC_I1386-INVOP,子码=为0x0)

我是Swift的新手,我认为这与强行打开有关,但我并不完全确定。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

可能导致此问题的两件事。

  • 首先,您可以确保在检索单元格时,您在func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell中的“单元格”对象中获得了某些内容。在您的手机上使用打印或只是测试。

  • 其次在func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)中使用storyboard?。你在哪里实例化它?它是否被建议作为自动完成解决方案。通常,要使用故事板,您以前需要像下面这样实例化它:let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)

第一次编辑解包网址:

if let url = URL(string: "https://" + selectedWebsite) {
   // URL unwrap with success
   webView.load(URLRequest(url: url)) 
   webView.allowsBackForwardNavigationGestures = true
} else {
  // Can't get URL
}