我在下面包含了我的代码的副本:
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 新手,我认为这与强制打开包装有关,但我不完全确定。任何帮助将不胜感激
最佳答案
可能有两件事导致此问题。
首先,您可以确保在检索单元格时,在
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 中的“cell”对象中获取某些内容
。在您的手机上使用 print 或仅进行测试。其次,在您的
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
中,您使用storyboard?
。你在哪里实例化它?是否建议将其作为自动完成解决方案。一般来说,要使用 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
}
关于通过 TableViewCell 加载网站时出现 Swift 可选错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46744655/