我想以编程方式生成具有特定大小的WKWebView。
这段代码是我到目前为止所得到的:
override func viewWillAppear(_ animated: Bool) {
let webview = WKWebView()
webview.frame = CGRect(width: UIScreen.main.bounds.width, height: 150) // not working
webview.load(URLRequest(url: (forResource: "index", withExtension: "html", subdirectory: "myfolder")! as URL) as URLRequest)
webview.uiDelegate = self
self.view.addSubview(webview)
}
但似乎并没有这样做。
错误:“无法转换类型'的值(forResource:String,withExtension:String,subirectory:String)'在强制中键入'URL'”
非常感谢任何帮助!
答案 0 :(得分:3)
Swift 5 。创建如下所示的WKWebView类型的变量
private let webView = WKWebView(frame: .zero)
在viewDidLoad()方法中,将webView添加到View。
webView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(self.webView)
// You can set constant space for Left, Right, Top and Bottom Anchors
NSLayoutConstraint.activate([
self.webView.leftAnchor.constraint(equalTo: self.view.leftAnchor),
self.webView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
self.webView.rightAnchor.constraint(equalTo: self.view.rightAnchor),
self.webView.topAnchor.constraint(equalTo: self.view.topAnchor),
])
// For constant height use the below constraint and set your height constant and remove either top or bottom constraint
//self.webView.heightAnchor.constraint(equalToConstant: 200.0),
self.view.setNeedsLayout()
var request = URLRequest(url: URL.init(string: "https://www.google.com"))
self.webView.load(request)
答案 1 :(得分:1)
我自己找到了解决方案:
此代码工作正常:
let webview = WKWebView()
webview.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100)
webview.load(URLRequest(url: Bundle.main.url(forResource: "index", withExtension:"html", subdirectory: "subdirectories")! as URL) as URLRequest)
self.view.addSubview(webview)
-
这是我失踪的那条线:
url: Bundle.main.url(forResource: "index", withExtension:"html", subdirectory: "subdirectories")! as URL)
答案 2 :(得分:0)
let webConfiguration = WKWebViewConfiguration()
let startScript = Bundle(for: Background.self).url(forResource: "my_js_script", withExtension: "js")!
let scripts = do {
return try String(contentsOf: startScript, encoding: .utf8)
}
catch {
let message = "Could not load file at: \(startScript)"
fatalError(message)
}
let script = WKUserScript(source: scripts, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true)
let contentController: WKUserContentController = WKUserContentController()
contentController.addUserScript(script)
contentController.add(self, name: "backgroundListener")
webConfiguration.userContentController = contentController
self._webView = WKWebView(frame: .zero, configuration: webConfiguration)
self._webView!.customUserAgent = "my-Bridge"
let html : String = """
<html>
<head></head>
<body></body>
</html>
""";
self._webView!.loadHTMLString(html, baseURL: nil)