top of page
Writer's pictureHui Wang

31. SwiftUI: Introducing WebKit

Today I will show you how to use view controls from other frameworks in the SwiftUI project.

SwiftUI doesn't provide a web view, so we need to use the web view in WebKit.


Steps:

  • First, we need to import the WebKit framework.

  • Make the current struct conform to the UIViewRepresentable protocol. With this protocol, UIView objects can be created and managed in SwiftUI.

  • Implement the makeUIView method in the protocol to initialize and return a WKWebView.

  • Then implement the updateUIView method in the protocol to set the URL parameters that the web view needs to load.

  • Initialize a URLRequest object as the URL of the web view.

  • Load the corresponding web page through the load method.




Source Code:

import SwiftUI
import WebKit

struct ContentView: UIViewRepresentable {
    
    func makeUIView(context: UIViewRepresentableContext<ContentView>) -> WKWebView {
        return WKWebView()
    }
    
    func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContext<ContentView>) {
        let request = URLRequest(url: URL(string: "https://www.podnu.com/")!)
        uiView.load(request)
    }
}

 

Follow me on:

Comments


bottom of page