SwiftUI Integrate with UIKit Tutorial

At the current state of SwiftUI not all views are implemented yet. UIKit views can be added in the Swift hierarchy. In this tutorial a url will be displayed in a web view. SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIIntegrateUIKitTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

A new webView needs to be created inside the project. Choose File -> New -> File and select iOS -> User Interface -> SwiftUI View. Name the file WebView.swift.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select WebView.swift. Change the code to

import SwiftUI
import WebKit

// 1.
struct WebView : UIViewRepresentable {
    let request: URLRequest
    // 2.
    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    // 3.
    func updateUIView(_ uiView: WKWebView, context: Context) {

struct WebView_Previews : PreviewProvider {
    static var previews: some View {
        // 4.
        WebView(request: URLRequest(url: URL(string: "https://ioscreator.com")!))
  1. The UIViewRepresentable protocol enabling an existing UIKit View to be added to a SwiftUI hierarchy

  2. The makeUIView(context:) method is required and creates the web view to be presented.

  3. The updateUI(context:) method is required and updated the presented web view to the latest configuration.

  4. The preview will display the url embedded in an url request

Go to the SceneDelegate.swift file and change the window.rootViewController = … line to

window.rootViewController = UIHostingController(rootView: WebView(request: URLRequest(url: URL(string: "https://ioscreator.com")!)))

Go to the preview pane and switch to live view. The preview will look like this.

The source code of the SwiftUIIntegrateUIKitTutorial can be downloaded at the ioscreator repository on Github.