繁体   English   中英

在Swift中以编程方式创建webView

[英]Creating webViews programmatically in Swift

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

在此输入图像描述

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

您可以使用这段代码尽可能简单地以编程方式创建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)
}

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

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")
}

对于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)
}

参考:基于@Deepakraj Murugesan提供的答案

尽管UIWebView可能不是您应该用于显示图像的东西,但您可以使用几行代码创建一个:

let webView = UIWebView(frame: someFrame)
webView.loadRequest(NSURLRequest(URL: someURL!))
view.addSubview(webView)

你不能这样做,原来,webview会占用大量内存,如果你使用了一些数量,可能会导致糟糕的体验,为什么不使用ImageView?

我认为SDWebImage + UIImageView会帮助你。 请参阅: https//github.com/rs/SDWebImage

对于Swift 4:

webView = WKWebView()
webView.navigationDelegate = self
view = webView

let url = URL(string: "https://www.earthhero.org")!
webView.load(URLRequest(url: url))
webView.allowsBackForwardNavigationGestures = true

另外,您需要导入WebKit并将WKNavigationDelegate添加到类中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM