March 2, 2024

Implement a WebView in SwiftUI

To use any UIKit component in SwiftUI, it needs to be wrapped with UIViewRepresentable.

  1. Create the wrapper struct:
This image has an empty alt attribute; its file name is image.png

2. UIViewRepresentable requires the ‘makeUIView’ and ‘updateUIView functions to be implemented:

This image has an empty alt attribute; its file name is image-1.png

3. Since we are wrapping a ‘WKWebView’ component, replace ‘some UIView’ with ‘WKWebView’ and ‘UIViewType’ with ‘WKWebView’:

This image has an empty alt attribute; its file name is image-2.png

4. Now we can develop the WebView wrapper to display web pages specified by a property called ‘urlString’:

This image has an empty alt attribute; its file name is image-3.png

Use the WebView wrapper as follows: