问题
I want to create something like an image gallery in my ViewController. For this, I'd need multiple webViews, depending on the number of images that I get from a JSON request. How can I insert new webViews if I need to?
As you can see in the above image, I have a scrollView and one UIWebView inside of the ViewController. How would I create a new webView inside of the first(second, third, etc.) if necessary? Is it possible?
回答1:
you can create the web view programatically as simple as possible use this piece of code
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)
}
and if you want use this delegate function
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")
}
回答2:
For 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)
}
Reference: Based on the answer provided by @Deepakraj Murugesan
回答3:
Although UIWebView is probably not the thing you should use for displaying images, you can create one with just a few lines of code:
let webView = UIWebView(frame: someFrame)
webView.loadRequest(NSURLRequest(URL: someURL!))
view.addSubview(webView)
回答4:
you can't do that, Originally,webview will take up a lot of memory, if you use some quantity of it, can lead to a bad experience, why do not use ImageView?
回答5:
I think SDWebImage + UIImageView will help you. See: https://github.com/rs/SDWebImage
回答6:
For 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
Plus you need to import WebKit and add WKNavigationDelegate to the Class.
来源:https://stackoverflow.com/questions/31650816/creating-webviews-programmatically-in-swift