- Published on
Creating a WebView with a transparent background in SwiftUI
- Authors

- Name
- Mick MacCallum
- @0x7fs
To create a WebView with a transparent background in SwiftUI, we can use a UIViewRepresentable to wrap a WKWebView. We need to set the isOpaque property to false and the backgroundColor property to .clear to achieve a transparent background.
import SwiftUI
import WebKit
struct TransparentWebView: UIViewRepresentable {
private let request: URLRequest
init(
url: URL,
cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy,
timeoutInterval: TimeInterval = 60.0
) {
request = URLRequest(
url: url,
cachePolicy: cachePolicy,
timeoutInterval: timeoutInterval
)
}
func makeUIView(context: Context) -> WKWebView {
let webview = WKWebView()
webview.load(request)
webview.allowsLinkPreview = false
webview.allowsBackForwardNavigationGestures = false
webview.isOpaque = false
webview.scrollView.backgroundColor = .clear
webview.backgroundColor = .clear
return webview
}
func updateUIView(_ uiView: WKWebView, context: Context) {
uiView.reload()
}
}
Continue Learning
SwiftUIImages
How to display a GIF from a URL in SwiftUI
Learn how to use a WKWebView as a quick way to load a GIF from a URL and display it in a SwiftUI view.
Read article
SwiftUIUIKit
Detect Successful Share Sheet Completion in SwiftUI
Learn how to detect when a user successfully shares content using a share sheet in SwiftUI by wrapping UIActivityViewController.
Read article
SwiftUIAppDelegate
Adding an App Delegate to a SwiftUI App
Learn how to integrate UIKit's App Delegate into your SwiftUI app for handling app lifecycle events and system callbacks.
Read article
