我的第一个ViewController中有一个tableView。它的功能之一就是这个
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Row \(indexPath.row) selected")
let mainStoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let webViewController = mainStoryboard.instantiateViewController(withIdentifier: "webViewController") as! webViewController
self.navigationController?.pushViewController(webViewController, animated: true)
}
如您所见,当要选择一行时,我想更改viewController,并且基于选择,我想在下一个ViewController上显示一个网站。我不知道如何将行值传递给下一个ViewController或在此函数中设置webView。
我想这样打开自己的网址,但可能在if-else语句中为每一行打开一个网址。
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string:"https://www.google.com")
let request = URLRequest(url: url!)
angebotWebView.load(request)
}
感谢您的帮助
答案 0 :(得分:2)
在您的webViewController
中创建一个字符串变量:
var urlString: String = "" // here
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: urlString) // put here
let request = URLRequest(url: url!)
angebotWebView.load(request)
OR
if let urlString = urlString, let url = URL(string: urlString) {
let request = URLRequest(url: url)
angebotWebView.load(request)
}
}
在这种方法中:-
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Row \(indexPath.row) selected")
let mainStoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let webViewController = mainStoryboard.instantiateViewController(withIdentifier: "webViewController") as! webViewController
webViewController. urlString = yourUrlArray[indexPath.row] // call it here
self.navigationController?.pushViewController(webViewController, animated: true)
}
答案 1 :(得分:1)
您可以从url
中取出viewDidLoad
,然后在didSelect
中创建实例时更改其值,如下所示:
@IBOutlet weak var webView: WKWebView!
var urlString:String?
override func viewDidLoad() {
super.viewDidLoad()
if let urlString = urlString, let url = URL(string: urlString) {
let request = URLRequest(url: url)
angebotWebView.load(request)
}
}
在tableView的didSelect方法中:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Row \(indexPath.row) selected")
let mainStoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let webViewController = mainStoryboard.instantiateViewController(withIdentifier: "webViewController") as! webViewController
webViewController.urlString = tableViewDataSource[indexPath.row]
self.navigationController?.pushViewController(webViewController, animated: true)
}
在这里,tableViewDataSource
是您用来显示列表的来源。
答案 2 :(得分:0)
首先,您需要在webViewController中创建var,例如
var url: String?
然后按如下所示调用webViewController
if let vc = storyboard.instantiateViewController(withIdentifier: "webViewController") as? webViewController {
vc.url = //indexPath.row
self.navigationController?.pushViewController(vc, animated: true)
}