我不知道我是否正确理解了您的问题。以下是我对您的问题的看法:
你的 MenuViewController 包含一个 UITableView,它是一个菜单列表,当一个单元格被选中时,你的 MainViewController 的 webview 会加载一个链接 URL,但是这个 URL 是放在 MenuViewController 中的,对吧?
如果这是您的问题,您可以通过以下解决方案解决:
MainViewController 添加通知观察者,MenuViewController 发布通知
// MainViewController
class ViewController: UIViewController {
let webView = UIWebView()
override func viewDidLoad() {
super.viewDidLoad()
webView.frame = self.view.bounds
self.view.addSubview(webView)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.handleNotification(_:)), name: "OpenURL", object: nil)
}
func handleNotification(notification:NSNotification) {
if let url = notification.userInfo?["url"] {
webView.loadRequest(NSURLRequest(URL: url as! NSURL))
}
}
}
// MenuViewController
class MenuViewController: UIViewController, UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let userInfo = ["url" : your_url]
NSNotificationCenter.defaultCenter().postNotificationName("OpenURL", object: nil, userInfo: userInfo)
}
}
更新:
如何使用 UITableView
class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView = UITableView(frame: CGRectZero, style: .Plain)
let urls = ["https://google.com", "https://youtube.com", "http://stackoverflow.com/"]
let cellIdentifier = "CellIdentifier"
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.frame = view.bounds
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
view.addSubview(tableView)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return urls.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
cell.textLabel?.text = urls[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let url = NSURL(string: urls[indexPath.row])!
let userInfo = ["url" : url]
NSNotificationCenter.defaultCenter().postNotificationName("OpenURL", object: nil, userInfo: userInfo)
}
}