I want a transparent web page in swift, so I have tried the below code according to this answer . Still, I am not getting a transparent web page. nothing changes in webview colour.. may I know why?? where am I going wrong? please help me in below code.
Total code:
import UIKit
import WebKit
class WebviewViewController: UIViewController {
@IBOutlet weak var testWebView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "https://developer.apple.com/swift/") else { return }
let request = URLRequest(url: url)
testWebView.load(request)
// Do any additional setup after loading the view.
self.testWebView = WKWebView()
self.testWebView!.isOpaque = false
self.testWebView!.backgroundColor = UIColor.clear
self.testWebView!.scrollView.backgroundColor = UIColor.clear
}
}
Please help me with the code.
the code to make transparent background is as follow what you already added.
self.testWebView!.backgroundColor = UIColor.clear
now question is you added right code already then why you are not getting reliable output ..?
Also , if you try self.testWebView!.alpha
with any value, it will affect all of WebPages
as WkWebView
is a single view and changing it's alpha will also affect the components within...
it happened because the page you load in WebViewController has some HTML
and CSS
code, you make your WebViewController transparent but because of that HTML
& CSS
you can't see it's transparency as each webpage
has it's own background color settings (which is merely impossible to change for each webpage
)
I hope you will understand and it will help you ...:)
as I see, you use storyboard ( @IBOutlet
) and you can use Storyboard for setting your WKWebView
:
And about code. This is enough for the result. You shouldn't set again self.testWebView = WKWebView()
, because you use storyboard and you can set isOpaque
with storyboard. As result:
class ViewController: UIViewController, WKNavigationDelegate {
@IBOutlet var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
let url = URL(string: "https://developer.apple.com/swift/")!
webView.load(URLRequest(url: url))
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let js = "(function() { document.body.style.background='transparent'; })();"
webView.evaluateJavaScript(js) { (_, error) in
print(error)
}
}
}
and evaluateJavaScript
helped to add transparency for background:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.