Reputation: 2351
In my project I have a view controller where i want to show WKWebView embedded inside another UIView titled viewForEmbeddingWebView that i've created in a storyboard (grey on the picture).
I've implemented this logic in my ViewController:
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
var webView: WKWebView!
@IBOutlet weak var viewForEmbeddingWebView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
webView = WKWebView(frame: viewForEmbeddingWebView.frame, configuration: WKWebViewConfiguration() )
self.viewForEmbeddingWebView.addSubview(webView)
self.webView.allowsBackForwardNavigationGestures = true
let myURL = URL(string: "https://www.apple.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
}
After build and running in Simulator I see the following:
It shows WKWebView but the bounds look wrong (first: it does not fit the viewForEmbeddingWebView's bounds and second: there is a white gap at the top). I've read that I must use WKWebView on the apple's site https://developer.apple.com/reference/webkit/wkwebview but their example is not my situation, because they only showing how to deal in the situation with loading WKWebView in the whole View of ViewController. But I need it to be embedded into another view because i will also need another ui later around this WKWebView. Before WKWebView there was WebView but since iOS 8 appeared we must use WKWebView. Please help, because i've checked lot of materials but have not find the answer working great with Swift 3 and Xcode 8.
I'm using Xcode 8 and Swift 3 with iOS 10.2.
Upvotes: 9
Views: 17007
Reputation: 59
WKWebView Swift 5 or Custom WKWebView(Webview deprecated) Please follow below the Apple link for WKWebView - https://developer.apple.com/documentation/webkit/wkwebview
If you want to add WKWebView in a custom view. Please follow the Code.
import WebKit
class OpenControllerURL: UIViewController,WKNavigationDelegate , WKUIDelegate {
@IBOutlet weak var CustomView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://developer.apple.com/documentation/webkit/wkwebview"!)
let request = URLRequest(url: url!)
let webView = WKWebView(frame: self.CustomView.frame)
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] //It assigns Custom View height and width
webView.navigationDelegate = self
webView.load(request)
self.CustomView.addSubview(webView)
}
#Happy Coding!!!
Upvotes: 5
Reputation: 6635
You want to initialize WKWebView
like this (Swift 3.0):
webView = WKWebView(frame: viewForEmbeddingWebView.bounds, configuration: WKWebViewConfiguration())
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.viewForEmbeddingWebView.addSubview(webView)
Upvotes: 30