Mastodon UIViewRepresentable – Josh Hrach

UIViewRepresentable: Accessing an underlying view

In the first post of this series, we looked at how we can display a UIView in a SwiftUI hierarchy, as well as how we can change properties on said view. In the second post, we explored options for exposing this view’s delegate to our SwiftUI view, allowing us to provide both an object to act as delegate as well as a way to respond to the delegate directly in the SwiftUI view.

Our demo code is presently:

class ThirdPartyUIView: UIView {
    var shouldAdd: Bool = true
    var delegate: ThirdPartyViewDelegate?
    
    // Same as button tap in view. Results reported via delegate
    func changeInternalValue() { /*...*/ }
}

struct ThirdPartyViewRepresentable: UIViewRepresentable {
    var delegate: ThirdPartyViewDelegate? = nil
    var shouldAdd: Bool
    
    func makeUIView(context: Context) -> ThirdPartyUIView {
        let view = ThirdPartyUIView()
        view.shouldAdd = shouldAdd
        view.delegate = delegate
        return view
    }
    
    func updateUIView(_ uiView: ThirdPartyUIView, context: Context) {
        uiView.shouldAdd = shouldAdd
    }
}

struct ThirdPartyView: View {
    var shouldAdd: Bool
    @State private var coordinator = ThirdPartyCoordinator()
    
    var body: some View {
        ThirdPartyViewRepresentable(delegate: coordinator, shouldAdd: shouldAdd)
    }
}

struct ThirdPartyDemoView: View {
    @State private var shouldAdd = true
    @State private var currentValue = 0
    
    var body: some View {
        Text("\(currentValue)")
        ThirdPartyView(shouldAdd: shouldAdd)
            .viewChangedValueTo { view, newValue in
                currentValue = newValue
            }
        Toggle("Add?", isOn: $shouldAdd)
        Button("Perform Action") {
            // ???
        }
    }
}

What does our Button‘s action need to be for us to trigger the ThirdPartyUIView.changeInternalValue() method?

There’s several ways we can solve this. One approach might be to have something trigger the action in the view representable’s updateUIView(_:context:) method. As noted in part one, updating the property on the UIViewRepresentable will trigger that method, so we just need to add properties for that to happen. So we could add a new @State boolean that is passed from our view down into the view representable, and when its value changes, we perform the action. However, this leaves us with a few oddities: To trigger the action, our button has to… toggle a Bool, which is not very obvious; Other developers might be confused as to what its purpose is. It also means that performing actions on the view requires changing state, which isn’t exactly why we have declarative UI frameworks like SwiftUI.

Instead of adding additional (and potentially confusing) state to our views to trigger actions, we really want our button to be able to just call the action that needs to be done. But that requires the action to be exposed in such a way that the Button can access it despite the action and its view living within another view. How can we expose that action in a way that the Button can trigger it? We’ll look at a few first party examples from SwiftUI. First, though, let’s look at how information is passed in SwiftUI.

Two-Way Communication

Normally we pass information from one view to the next by means of the view’s initializer. For instance, providing an initial value for shouldAdd in our example is part of the call site.

ThirdPartyView(shouldAdd: shouldAdd)

What if we needed to pass information down through multiple layers of views? That’s where the environment comes into play.

There are two ways of passing information down through the environment.1 The first is by passing in an EnvironmentObject. Essentially, by providing a class object conforming to ObservableObject, you can then listen for said object in a sub-view.

// Creating your object
class SomeObject: ObservableObject { }
let yourObject = SomeObject()

...

// Adding it to the environment of some view
SomeSwiftUIView()
    .environmentObject(yourObject)


struct SomeSwiftUIView: View {
    // Retrieving object from enviroment
    @EnvironmentObject private var yourObject: SomeObject
}

The second way is by means of EnvironmentValues. This struct is used anytime you pull information from the environment. Here are a few things you can get from the environment in SwiftUI.

@Environment(\.colorScheme) var colorScheme
@Environment(\.dynamicTypeSize) var typeSize

The Environment wrapper takes a key path to a property on EnvironmentValues. The property we create as a var inherits its type from the property the key path points to. In these examples, both colorScheme and dynamicTypeSize are just properties exposed on the EnvironmentValues struct.

So the environment is used to pass data down the hierarchy. How can we pass information up? That is by means of Preferences.

Whereas you use the environment to configure the subviews of a view, you use preferences to send configuration information from subviews toward their container. However, unlike configuration information that flows down a view hierarchy from one container to many subviews, a single container needs to reconcile potentially conflicting preferences flowing up from its many subviews.

Apple Documentation

To pass information via Preferences, one needs to create a struct conforming to PreferenceKey. This is a named value that is produced by the view. Part of the creation of the PreferenceKey is resolving multiple values for that key into a single value. That single value can then be used by a parent container view.

Now that we’ve checked out the ways we can communicate up and down a SwiftUI view hierarchy, there’s one more thing SwiftUI can teach us. Are there any examples of exposing underlying functionality to a parent container? The answer is actually yes.

Proxies

While the debate of UIKit versus SwiftUI continues among developers, many often forget one simple truth: SwiftUI is quite often just utilizing UIKit under the hood. This is why development techniques that manipulate underlying UIKit views are possible.

This truth, however, leads many to say that SwiftUI is lacking because things that are possible in UIKit are simply not exposed. This is true for elements where tasks might be trigger programmatically but are difficult to describe as a function of state. Let’s consider the ScrollView.

ScrollView {
    Text("First").id(1)
    Text("Second").id(2)
    Text("Third").id(3)
}

A ScrollView tells us to put its contents inside of, well, a scroll view. When we create it, we can tell it which axis to scroll on. However, UIScrollView in UIKit does more than that; it allows programmatic scrolling! How did Apple end up adding that functionality?

Introducing the ScrollViewReader.

ScrollViewReader { proxy in
    ScrollView {
        Text("First").id(1)
        Text("Second").id(2)
        Text("Third").id(3)
    }
}

The sole purpose of the ScrollViewReader is to expose functionality of underlying scroll views, in this case the ability to scroll to a particular view. It does so by means of a proxy object. We pass that proxy the ID of the object we want to scroll to.

ScrollViewReader { proxy in
    ScrollView {
        Text("First").id(1)
        Text("Second").id(2)
        Text("Third").id(3)
        Button("Scroll To Top") {
            proxy.scrollTo(1)
        }
    }
}

If we need to have programmatic control, we use the ScrollViewReader. If we just need a ScrollView without that, we can ignore it. Can we create something similar for our example? Could we end up with something like this?

ThirdPartyReader { proxy in 
    ThirdPartyView()
    Button("Perform Action") {
        proxy.changeInternalValue()
    }
}

Creating a Proxy and a Reader

To achieve our goal, we need to create a few new objects. First, our proxy. This object’s purpose is to expose functionality of the ThirdPartyUIView without exposing the entire view itself. The design is fairly simple. 2

class ThirdPartyProxy {
    fileprivate weak var view: ThirdPartyUIView?
    
    func changeInternalValue() {
        view?.changeInternalValue()
    }
}

Our proxy has a single method, changeInternalValue(). If there were other functions of ThirdPartyUIView that we’d want to expose, we would add them here.

Now, how will we expose the proxy? We’ll copy the above example and build our own “reader” object.

struct ThirdPartyReader<Content: View>: View {
    private var content: (ThirdPartyProxy) -> Content
    
    init(@ViewBuilder _ content: @escaping (ThirdPartyProxy) -> Content) {
        self.content = content
    }
    
    var body: some View {
        content(proxy)
    }
}

The ThirdPartyReader‘s purpose is to provide a proxy instance to our view content. It’s a very simple container! However, how will we get the proxy? And how will the proxy get the view?

Here, there are 2 approaches we could take: (1) We can pass the view or its actions up through Preferences to this container, or (2) pass an object into the Environment that captures what we need.

For now, we’ll go with option 2. Option 1 is definitely possible but has its own quirks. If you build a good example using it, I’d love to hear about it!

Getting the View for Our Proxy

We’re working down through the hierarchy in the Environment. Thus, we start by creating a proxy instance in our new reader.

struct ThirdPartyReader<Content: View>: View {
    @StateObject private var proxy = ThirdPartyProxy()

Note that we’re creating this as a StateObject. Our reader is thus owning the instance of this object. However, using this property wrapper requires our proxy conform to ObservableObject. We’ll do so as precedent as a proxy might benefit from having @Published properties depending on the view being wrapped.

With the proxy created and owned by this view, we now pass it into the Environment. However, we’re not just passing it using .environmentObject. Doing so would create a tight requirement for any child view, where we must provide a proxy even if we’re not in a reader.

Instead, we’ll make use of the EnvironmentValues.

extension EnvironmentValues {
    private struct ThirdPartyProxyEnvironmentKey: EnvironmentKey {
        static var defaultValue: ThirdPartyProxy? = nil
    }
    
    var thirdPartyProxy: ThirdPartyProxy? {
        get { self[ThirdPartyProxyEnvironmentKey.self] }
        set { self[ThirdPartyProxyEnvironmentKey.self] = newValue }
    }
}

We first create a new EnvironmentKey. It tells us the type to be passed into the environment which will be an optional ThirdPartyProxy. By default, it’ll be nil, which means no proxy exists in the environment.

We’ll use the above to pass our new proxy into the environment of the reader’s view.

var body: some View {
    content(proxy)
        .environment(\.thirdPartyProxy, proxy)
}

Now, any view content provided to the reader container will find a proxy object in the environment. We can now check the environment in our ThirdPartyView and update our view representable to set the view on that proxy.

struct ThirdPartyViewRepresentable: UIViewRepresentable {
    @State private var actionTriggered = false
    
    var delegate: ThirdPartyViewDelegate? = nil
    var proxy: ThirdPartyProxy?
    var shouldAdd: Bool
    
    func makeUIView(context: Context) -> ThirdPartyUIView {
        let view = ThirdPartyUIView()
        view.shouldAdd = shouldAdd
        view.delegate = delegate
        proxy?.view = view
        return view
    }
    
    func updateUIView(_ uiView: ThirdPartyUIView, context: Context) {
        uiView.shouldAdd = shouldAdd
    }
}
struct ThirdPartyView: View {
    @Environment(\.thirdPartyProxy) private var proxy
    
    var shouldAdd: Bool
    @State private var coordinator = ThirdPartyCoordinator()
    
    var body: some View {
        ThirdPartyViewRepresentable(delegate: coordinator, proxy: proxy, shouldAdd: shouldAdd)
    }
}

With the above changes, we’ve added the last piece and have enabled our SwiftUI views to access underlying methods of our wrapped UIView. Our fully functional sample view now looks like this:

struct ThirdPartyDemoView: View {
    @State private var shouldAdd = true
    @State private var currentValue = 0
    
    var body: some View {
        ThirdPartyReader { proxy in
            Text("\(currentValue)")
            ThirdPartyView(shouldAdd: shouldAdd)
                .viewChangedValueTo { view, newValue in
                    currentValue = newValue
                }
            Toggle("Add?", isOn: $shouldAdd)
            Button("Perform Action") {
                proxy.changeInternalValue()
            }
        }
    }
}

In these posts, we’ve looked at how we can fully use a UIView within a SwiftUI hierarchy. To do so, we’ve simply used what Apple has provided since SwiftUI was introduced with iOS 13. And while SwiftUI might be the future of building apps, it will likely continue to be built on top of UIKit, and UIKit likely has a long future ahead of it. Being able to work with UIKit in SwiftUI is just another tool in our ever growing toolbox as developers on Apple platforms.

The full sample code is available as a Github Gist.

  1. When speaking about the environment and its usage, I’ll be referring to APIs and terminology from before iOS 17. iOS 17 has made some changes to Environment and includes the new Observable framework, neither of which I’ll be discussing here. ↩︎
  2. This variable is declared as fileprivate just so that the view property is exposed to the other classes in this file but not to the consumers of the API we’re building. If you’re adding this into a framework or library, then keeping this property internal while making the functions you add public will satisfy this requirement, too.

    We also make this weak so that it doesn’t retain the view it is referencing. ↩︎

UIViewRepresentable: Working with delegates in SwiftUI

In the first post of this series, we looked at how we can display a UIView in a SwiftUI hierarchy, as well as how we can change properties on said view. As a refresher, here is our example.

Imagine we have a third party SDK that provides their functionality in a pre-packaged UIView subclass. We’ll call this ThirdPartyUIView. It has properties set on it to change its behavior, methods that can be called on it, and provides internal feedback by means of a delegate object.

class ThirdPartyUIView: UIView {
    var shouldAdd: Bool
    var delegate: ThirdPartyViewDelegate?
    
    // Same as button tap in view. Results reported via delegate
    func changeInternalValue() { /*...*/ }
}

protocol ThirdPartyViewDelegate {
    func view(_ view: ThirdPartyUIView, changedValueTo newValue: Int)
}

And here is our UIViewRepresentable view thus far.

struct ThirdPartyViewRepresentable: UIViewRepresentable {
    var shouldAdd: Bool
    
    func makeUIView(context: Context) -> ThirdPartyUIView {
        let view = ThirdPartyUIView()
        view.shouldAdd = shouldAdd
        return view
    }
    
    func updateUIView(_ uiView: ThirdPartyUIView, context: Context) {
        uiView.shouldAdd = shouldAdd
    }
}

How can we provide a delegate when creating our view? Let’s look at a few approaches.

The Coordinator

The UIViewRepresentable protocol gives us one approach that we can take. The clue is found in the Context object that is provided in both the makeUIView(context:) and updateUIView(_:context:) methods. It has a coordinator property of type Coordinator. But what is this type?

Here is how it is defined in the UIViewRepresentable protocol:

/// A type to coordinate with the view
associatedtype Coordinator = Void

By default, Coordinator is type Void, essentially meaning an empty type. It is provided to the Context by means of the protocol method makeCoordinator(). By providing our own type here, we can create an object that will coordinate with the view.

Let’s use that to create a type conforms to the ThirdPartyViewDelegate protocol. We can then create an instance of it and provide it when we initialize our view.

struct ThirdPartyViewRepresentable: UIViewRepresentable {
    class Coordinator: ThirdPartyViewDelegate {
        func view(_ view: ThirdPartyUIView, changedValueTo newValue: Int) {
            // Respond to newValue
        }
    }
    
    var shouldAdd: Bool
    
    func makeUIView(context: Context) -> ThirdPartyUIView {
        let view = ThirdPartyUIView()
        view.shouldAdd = shouldAdd
        view.delegate = context.coordinator
        return view
    }
    
    func updateUIView(_ uiView: ThirdPartyUIView, context: Context) {
        uiView.shouldAdd = shouldAdd
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator()
    }
}

Just like that, we’ve been able to define and provide a delegate that can respond to changes to the ThirdPartyUIView!

However, we have some limitations here. First, this means that the delegate is defined and created entirely within the ThirdPartyViewRepresentable. There isn’t any way to provide a different delegate. We also have no way to allow this delegate to interface with other elements, such as some kind of UI within our SwiftUI hierarchy. How can we allow that?

Injecting a Delegate

The simplest way is by creating our delegate class outside of the view representable and providing an instance of it when we initialize the view.

class OurDelegate: ThirdPartyViewDelegate {
    func view(_ view: ThirdPartyUIView, changedValueTo newValue: Int) {
        // Respond to newValue
    }
}

struct ThirdPartyViewRepresentable: UIViewRepresentable {
    var delegate: ThirdPartyViewDelegate? = nil
    var shouldAdd: Bool
    
    func makeUIView(context: Context) -> ThirdPartyUIView {
        let view = ThirdPartyUIView()
        view.shouldAdd = shouldAdd
        view.delegate = delegate
        return view
    }
    
    func updateUIView(_ uiView: ThirdPartyUIView, context: Context) { ... }
}

Now, when we make use of the view representable, we have the option of providing a delegate.

struct ThirdPartyDemoView: View {
    @State private var shouldAdd = true
    private let delegate = OurDelegate()
    
    var body: some View {
        ThirdPartyViewRepresentable(delegate: delegate, shouldAdd: shouldAdd)
        Toggle("Add?", isOn: $shouldAdd)
    }
}

This is great because we can provide any delegate we want for the underlying view. If we use this view in multiple places or in multiple projects, we can create a different delegate based on each situation. However, we still don’t have a way for these updates to be exposed in our SwiftUI view. For instance, what if we wanted a Text view to display the new value? How could we change our view to support that?

To answer, let’s first take a step back and consider how we might want our code to be written.

Planning Our API

As we build our own implementations, it’s sometimes helpful to look at existing first party code. For example, let’s look at how SwiftUI exposes various actions that we can respond do.

One example is .onAppear(perform:), which lets us declare a closure that is called when the view appears. This sounds like what we want to emulate. Providing a closure of our own to perform when a delegate method is invoked would be a good way to hook into the delegate while letting us access the data in our SwiftUI view. So our destination is something like this:

// What we'd like to build
ThirdPartyView()
    .viewChangedValueTo { thirdPartyView, newValue in 
        // Use newValue to update some state in our view
        // Access thirdPartyView if necessary
    }

What do we need to do to create the above?

To begin, let’s first add another layer of abstraction around our view representable.

struct ThirdPartyView: View {
    var shouldAdd: Bool
    
    var body: some View {
        ThirdPartyViewRepresentable(delegate: ???, shouldAdd: shouldAdd)
    }
}

Like before, we will initialize this view with a shouldAdd property so we can control it externally. But what about our delegate? What should we put there? We’ll need to create a class that can act as a ThirdPartyViewDelegate that takes the data from the delegate method and forwards it to a closure that we define.

class ThirdPartyCoordinator: ThirdPartyViewDelegate {
    var viewChangedValueTo: ((ThirdPartyUIView, Int) -> Void)?
    
    func view(_ view: ThirdPartyUIView, changedValueTo newValue: Int) {
        viewChangedValueTo?(view, newValue)
    }
}

When the delegate method is called, it’ll pass on its parameters to the viewChangedValueTo closure. We will now use the above coordinator as our representable’s delegate.

struct ThirdPartyView: View {
    var shouldAdd: Bool
    @State private var coordinator = ThirdPartyCoordinator()
    
    var body: some View {
        ThirdPartyViewRepresentable(delegate: coordinator, shouldAdd: shouldAdd)
    }
}

Note two things. First, we declare this private; the existence of the coordinator is purely an implementation detail of ThirdPartyView and not something that would need to be changed from the outside. Second, we declare it as a @State property. Though we won’t be changing its value, it now ties the existence of the coordinator along with the view. That will be important for what we do next.

Next, we’ll create our view modifier. However, we wouldn’t want it to work with all Views; this is only important if we’re using a ThirdPartyView. Well, looking again at SwiftUI, certain views, such as Image, come with their own modifiers. Instead of being declared as extensions on View, they exist as extensions of a particular type. We’ll do the same and create this view modifier in an extension of our view. Its purpose is to allow us to set the closure that will be called when the delegate method is hit.

extension ThirdPartyView {
    func viewChangedValueTo(_ closure: @escaping (_ view: ThirdPartyUIView, _ newValue: Int) -> Void) -> Self {
        coordinator.viewChangedValueTo = closure
        return self
    }
}

With this extension, we provide a closure that is called when the delegate method is called. If there were other methods as part of the delegate protocol, we could likewise expose them to SwiftUI in the same manner.

One additional change I like doing here is adding support for providing an entire delegate object to respond to these delegate calls. To do that, we’ll modify our coordinator to hold another delegate to forward calls to and add a view modifier that lets us set that delegate.

class ThirdPartyCoordinator: ThirdPartyViewDelegate {
    var viewChangedValueTo: ((ThirdPartyUIView, Int) -> Void)?
    var externalDelegate: ThirdPartyViewDelegate?
    
    func view(_ view: ThirdPartyUIView, changedValueTo newValue: Int) {
        viewChangedValueTo?(view, newValue)
        externalDelegate?.view(view, changedValueTo: newValue)
    }
}

extension ThirdPartyView {
    func setViewDelegate(_ delegate: ThirdPartyViewDelegate) -> Self {
        coordinator.externalDelegate = delegate
        return self
    }
}

With this addition, not only can we respond to delegate methods directly in our SwiftUI view, but we also can provide a delegate class to handle those as well.

The ThirdPartyUIView, its properties, and its delegate are now usable in SwiftUI like so.

struct ThirdPartyDemoView: View {
    @State private var shouldAdd = true
    @State private var currentValue = 0
    
    // Use our delegate for something like logging all delegate usage
    private let delegate = OurDelegate()
    
    var body: some View {
        Text("\(currentValue)")
        ThirdPartyView(shouldAdd: shouldAdd)
            .viewChangedValueTo { view, newValue in
                currentValue = newValue
            }
            .setViewDelegate(delegate)
        Toggle("Add?", isOn: $shouldAdd)
    }
}

ThirdPartyView communicates with our underlying ThirdPartyUIView via a view representable internally. The view’s shouldAdd property is exposed and can be changed by our Toggle. And we have full access to the view’s delegate by providing an object conforming to the delegate protocol or by providing closures via view modifiers for the specific delegate methods we want to work with.

However, there’s still one piece missing. Let’s add one more piece to the view:

struct ThirdPartyDemoView: View {
    @State private var shouldAdd = true
    @State private var currentValue = 0
    
    private let delegate = OurDelegate()
    
    var body: some View {
        Text("\(currentValue)")
        ThirdPartyView(shouldAdd: shouldAdd)
            .viewChangedValueTo { view, newValue in
                currentValue = newValue
            }
            .setViewDelegate(delegate)
        Toggle("Add?", isOn: $shouldAdd)
        Button("Perform Action") {
            // ???
        }
    }
}

Here, we’ve added a Button. Why? Simple: we want to trigger the view’s action programmatically! But how can we expose the view’s action to make it accessible to our Button?

UIViewRepresentable: Showing UIKit components in SwiftUI

SwiftUI was unveiled to the world at WWDC in 2019. Since its introduction, Apple has offered a way for SwiftUI to bring in UIKit components. How does that work? And how can we build solutions to communicate from UIKit to SwiftUI and vice versa? This multi-part series will look into answers to those questions one piece at a time.

Our Example

Imagine we have a third party SDK that provides their functionality in a pre-packaged UIView subclass. 1 We’ll call this ThirdPartyUIView. It has properties set on it to change its behavior, methods that can be called on it, and provides internal feedback by means of a delegate object. Let’s use this as our very basic example:

class ThirdPartyUIView: UIView {
    var shouldAdd: Bool
    var delegate: ThirdPartyViewDelegate?
    
    // Same as button tap in view. Results reported via delegate
    func changeInternalValue() { /*...*/ }
}

protocol ThirdPartyViewDelegate {
    func view(_ view: ThirdPartyUIView, changedValueTo newValue: Int)
}

As you can see, our example ThirdPartyUIView has a boolean that can change internal behavior to either add or subtract a value, as well as a delegate that is notified whenever this internal state (we’re using an Int as an example) is changed. Lastly, we’ll assume this view has a button that changes this internal value, and the action performed by that button is exposed for us to call programmatically.

With this defined, let’s explore how we can work with this view and all of its functionality in SwiftUI.

Displaying a UIView

First, how do we get a UIView to appear in SwiftUI? This is where UIViewRepresentable can help us. 2 We declare a struct that conforms to this type. Its purpose is to provide the underlying UIView type that we want to wrap and display, as well as functions for creating and updating said view.

struct ThirdPartyViewRepresentable: UIViewRepresentable {
    func makeUIView(context: Context) -> ThirdPartyUIView {
        let view = ThirdPartyUIView()
        
        return view
    }
    
    func updateUIView(_ uiView: ThirdPartyUIView, context: Context) {
        
    }
}

With the code above, we can now use our ThirdPartyUIView in a SwiftUI hierarchy. For example:

struct ThirdPartyDemoView: View {
    var body: some View {
        ThirdPartyViewRepresentable()
    }
}

If we loaded this view, we would see our ThirdPartyUIView within our SwiftUI application. However, because we haven’t exposed any functionality, we can’t really do anything with the view yet. Let’s change that.

Updating View Properties

Let’s start with changing properties on the underlying view. As you’ll recall above, our ThirdPartyUIView includes a shouldAdd property. If true, each action performed by the view will add one to the internal value; false will have it subtract instead.

First, we want to allow this option to be set when we create the view. To do so, we need to provide it when creating our view representable.

struct ThirdPartyViewRepresentable: UIViewRepresentable {
    var shouldAdd: Bool
    
    func makeUIView(context: Context) -> ThirdPartyUIView {
        let view = ThirdPartyUIView()
        view.shouldAdd = shouldAdd 
        return view
    }
    
    func updateUIView(_ uiView: ThirdPartyUIView, context: Context) {
        
    }
}

Now, when we create our view, we can provide a value that will be used when initializing the view. As this is something we might want to change as we use it, we’ll add it as a @State property on our view along with a Toggle that will let us change it as needed.

struct ThirdPartyDemoView: View {
    @State private var shouldAdd = true
    
    var body: some View {
        ThirdPartyViewRepresentable(shouldAdd: shouldAdd)
        Toggle("Add?", isOn: $shouldAdd)
    }
}

However, we’ve now got an issue. If you change the value of the Toggle, behavior of the view doesn’t change! Why?

When the value of shouldAdd changes, the underlying view is not recreated, so makeUIView(context:) is not called again. Rather, the view is updated. Thus, we need to update the property inside of the updateUIView(_:context:) method. 3

struct ThirdPartyViewRepresentable: UIViewRepresentable {
    var shouldAdd: Bool
    
    func makeUIView(context: Context) -> ThirdPartyUIView {
        let view = ThirdPartyUIView()
        view.shouldAdd = shouldAdd
        return view
    }
    
    func updateUIView(_ uiView: ThirdPartyUIView, context: Context) {
        uiView.shouldAdd = shouldAdd
    }
}

With the above addition, when we toggle the state of shouldAdd, the view now updates and behaves as expected.

Now that we can change properties on the underlying UIView, let’s look at how we can expose the ThirdPartyViewDelegate.


  1. While this series of posts will explore exposing and working with a third party’s UIView in our own SwiftUI views, these tips can also apply to taking your own existing UIKit code and using it in SwiftUI yourself. ↩︎
  2. When working with UIKit, we also have UIViewControllerRepresentable. On the Mac with AppKit, NSViewControllerRepresentable and NSViewRepresentable exist as counterparts. This post talks exclusively about UIViewRepresentable but the principles will apply to the other representable options as well. ↩︎
  3. While we’re working with a single property, there can be some gotchas when dealing with multiple properties, or when trying to update parts of a view that make cause state changes. Chris Eidhof has a great post with some examples of these gotchas. ↩︎