avatar
Published on

Creating a WebView with a transparent background in SwiftUI

Authors
  • avatar
    Name
    Mick MacCallum
    Twitter
    @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()
    }
}