gpt4 book ai didi

ios - 使用不同 ViewController 中的按钮更改 WKWebview URL

转载 作者:行者123 更新时间:2023-11-30 13:18:27 24 4
gpt4 key购买 nike

我对 iOS 开发非常陌生,想尝试使用 webview 构建混合 iOS 应用程序。我一直在学习,并在此处或其他网站找到了我需要的大部分答案,但我已经陷入了困境。

我在主 ViewController 中设置了 webview,一切都加载得很好。我正在使用一个库来创建一个效果很好的侧面菜单。然而,由于库的工作方式,菜单是在另一个 ViewController 中构建的。我想用将在 WebView 中加载的链接填充侧面菜单。这可能吗?

编辑:我可能还应该提到我正在 swift 完成这一切。

编辑2:这是我用于侧菜单的框架的链接:https://github.com/jonkykong/SideMenu

该框架几乎允许您使用 TableView 构建自己的 View 。

最佳答案

不知道我是否正确理解了你的问题。以下是我对你的问题的看法:

你的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)
}
}

关于ios - 使用不同 ViewController 中的按钮更改 WKWebview URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38009295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com