Since there are some components not available in SwiftUI, we can adapt some from UIKit. This is necessary when, for example, we want to implement a delegate
.
Let's look at the example of a WKWebView
that we want to load in our SwiftUI code, and we also want to implement WKNavigationDelegate
, which will notify us when the web content has finished loading.
The first step is to create a struct
(which we've called "WebView") that implements the UIViewRepresentable
protocol. This struct
has three parts:
- The
URLRequest
, which we will define from our view later. - The
makeUIView(context:)
function, where we must return the component we want to load, in this case, aWKWebView
. - The
updateUIView(_:, context:)
function, which will be triggered when the system detects an important UI update, for example, when our screen is loaded. We will use it to load theURLRequest
in our WebView.
import WebKit
struct WebView: UIViewRepresentable {
let request: URLRequest
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
func updateUIView(_ uiView: WKWebView, context: Context) {
uiView.load(request)
}
}
Continue reading
Access to all the content with our plans.
- Junior level content
- Senior level content
- Expert level content
- Extra content
- Question submissions
Monthly
Yearly
Be the first to comment