Xcode在另一个ViewController中打开WebView

时间:2017-01-24 13:32:44

标签: ios swift xcode uiviewcontroller uiwebview

我尝试使用启动webview的按钮制作应用程序。

我已经关注了许多有关该主题的教程和阅读不同主题但我无法使其正常工作:我在测试代码时收到此消息:

    "Cannot call value of non-function type UIWebView!"

这是我到目前为止所做的步骤

  • 在主视图Controller
  • 中添加按钮
  • 创建另一个名为' WebViewController'
  • 的视图
  • 添加segue以将按钮链接到WebViewController
  • 创建新的Cocoa Touch类文件' WebViewController'
  • 使用WebViewController类设置WebViewController自定义类
  • 在名为' myWebView'
  • 的WebViewController ViewController中添加webView

这是WebViewController类(我在运行项目时遇到错误)

  import UIKit

  class WebViewController: UIViewController{

  @IBOutlet weak var myWebView: UIWebView!

  override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    //define url
    let url = NSURL (string: "http://www.my-url.com")
    //request
    let req = NSURLRequest(url: url as! URL)
    //load request into the webview
    myWebview(req as URLRequest) //error happens here : 
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

这是一个截图(图片说明的不只是长文本,右边=) enter image description here

谢谢!

2 个答案:

答案 0 :(得分:0)

尝试使用:

  let url = NSURL (string: "https://google.com")
  let request = NSURLRequest(url: url as! URL)
  self. myWebView.loadRequest(request as URLRequest)

此代码适用于我

答案 1 :(得分:0)

您可以使用SFSafariViewController:

import SafariServices

let url = URL(string: "https://www.google.com")
let safariVC: SFSafariViewController = SFSafariViewController(url: url)

self.present(safariVC, animated: true, completion: nil)

我使用了swift 3语法。 该代码打开了Safari Web视图,您无需在故事板中创建segues和view controlles。