在Swift中以编程方式创建webView

Ork*_*ade 11 uiwebview webview ios swift

我想在我的ViewController中创建类似图像库的东西.为此,我需要多个webView,具体取决于我从JSON请求获得的图像数量.如果需要,我如何插入新的webView?

在此输入图像描述

正如您在上图中看到的,我在ViewController中有一个scrollView和一个UIWebView.如有必要,我如何在第一个(第二个,第三个等)内创建一个新的webView?可能吗?

Dee*_*san 23

您可以使用这段代码尽可能简单地以编程方式创建Web视图

override func viewDidLoad() {
    super.viewDidLoad()
    let webV:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
    webV.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.google.co.in")))
    webV.delegate = self;
    self.view.addSubview(webV)
}
Run Code Online (Sandbox Code Playgroud)

如果你想使用这个委托功能

func webView(webView: UIWebView!, didFailLoadWithError error: NSError!) {
    print("Webview fail with error \(error)");
}
func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
    return true;
}
func webViewDidStartLoad(webView: UIWebView!) {
    print("Webview started Loading")
}
func webViewDidFinishLoad(webView: UIWebView!) {
    print("Webview did finish load")
}
Run Code Online (Sandbox Code Playgroud)


kur*_*odu 5

对于Swift 3:

override func viewDidLoad() {
    super.viewDidLoad()
    let webV    = UIWebView()
    webV.frame  = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
    webV.loadRequest(NSURLRequest(url: NSURL(string: "https://www.apple.com")! as URL) as URLRequest)
    webV.delegate = self
    self.view.addSubview(webV)
}
Run Code Online (Sandbox Code Playgroud)

参考:根据@Deepakraj Murugesan提供的答案