UIViewRepresentable
Using UIKit elements on SwiftUI.
UIViewRepresentable
Using UIKit elements on SwiftUI.
0
0
Checkbox to mark video as read
Mark as read

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, a WKWebView.
  • 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 the URLRequest 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.

Basic Plan

FREE

Start Now
  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • Question submissions
Monthly
Yearly

Plan logo

-

Unlimited access to the whole content

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • Question submissions

Stripe secure payment methods
Plan logo

-

Unlimited access to the whole content

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • Question submissions

Stripe secure payment methods
Plan logo

-

Solve your doubts at any level

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • 2 Question submissions per week

Stripe secure payment methods
Plan logo

-

Solve your doubts at any level

  • Junior level content
  • Senior level content
  • Expert level content
  • Extra content
  • 2 Question submissions per week

Stripe secure payment methods

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy