用 prepare 傳遞資料 — 愛瘋一切為蘋果的彼得潘




呼叫 prepare 傳遞資料給 WebViewController

利用 tableView.indexPathForSelectedRow?.row 去抓點選的 tableViewCell,再將 row 傳給 WebViewController

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
let controller = segue.destination as? WebViewController
if let row = tableView.indexPathForSelectedRow?.row {
controller?.row = row
}
}

WebViewController 的 viewDidLoad 呼叫 function 回傳 URL 字串後,再利用 WKWebView 顯示網頁

@IBOutlet weak var myWebView: WKWebView!
var row = 0
func getURL(row: Int) -> String {
if row == 0 {
return "http://apppeterpan.strikingly.com/?fbclid=IwAR1QdwwVkPuQsuVWqXzkIx-6IQ0KYCdv5wpArQNj4GuIjOBNcjYjVgYru5g"
}else if row == 1 {
return "http://swiftbook.strikingly.com"
}else if row == 2 {
return "http://peterpaniosapp.strikingly.com"
}else {
return "http://learniosfromzero.strikingly.com"
}
}

override func viewDidLoad() {
super.viewDidLoad()
let url = getURL(row: row)
if let url = URL(string: url) {
let request = URLRequest(url: url)
myWebView.load(request)
}
// Do any additional setup after loading the view.
}

記得要

import WebKit