Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 46 ยท Polish and Platform Features

UIKit Interoperability

Mix SwiftUI and UIKit in one app: wrap UIKit views with UIViewRepresentable, use coordinators for delegates, embed SwiftUI with UIHostingController, and know when to use each.

SwiftUI is not an island. UIKit has been the foundation of iOS since 2008, and it still powers huge codebases, mature libraries and a few features that SwiftUI covers late or only partly. The good news is that the two frameworks are designed to be mixed in both directions. You can put a UIKit view inside a SwiftUI screen, and you can put a SwiftUI screen inside a UIKit app, one piece at a time.

This lesson explains the two bridges, the Representable protocols that wrap UIKit for SwiftUI and UIHostingController that wraps SwiftUI for UIKit, the coordinator that carries delegate callbacks back to SwiftUI, and a practical rule for when to drop down to UIKit at all. UIKit code needs a device or simulator, so the real snippets are read-only. The two TryIts are stand-ins that model the bridge in plain Swift so you can watch the lifecycle and the coordinator at work. You should know @State and @Binding and the SwiftUI mental model.

Two directions of interop

UIKit in SwiftUI Wrap a view with UIViewRepresentable.
SwiftUI in UIKit Host a view with UIHostingController.

Both work screen by screen, so migration can be gradual.

1 / 2

UIKit versus SwiftUI at a glance

The two frameworks solve the same problem with different styles. Knowing the contrast makes the bridge easier to understand.

UIKit SwiftUI
Style Imperative: create objects, mutate them Declarative: describe UI for the current state
UI building blocks UIView and UIViewController classes View structs
Layout Auto Layout constraints and frames Proposed-size negotiation with stacks
Updating You change views by hand State changes re-run body
Events Delegates, target-action, notifications Closures, bindings, modifiers
Lifecycle viewDidLoad, viewWillAppear, deinit onAppear, task, identity
Lists UITableView, UICollectionView List, LazyVStack, Grid
Maturity Very deep control and many edge cases Faster to write, some gaps

UIKit views are reference types with identity: one object lives for a long time and you keep changing it. SwiftUI views are cheap value descriptions recreated constantly. A bridge has to reconcile those two models, which is exactly what the representable protocols do.

UIViewRepresentable: UIKit inside SwiftUI

To use a UIKit view in SwiftUI, create a struct that conforms to UIViewRepresentable. The simplest case is a spinner that SwiftUI did not originally offer in the shape you needed:

Swift
import SwiftUI
import UIKit

struct Spinner: UIViewRepresentable {
    var isAnimating: Bool

    func makeUIView(context: Context) -> UIActivityIndicatorView {
        let view = UIActivityIndicatorView(style: .large)
        view.hidesWhenStopped = true
        return view
    }

    func updateUIView(_ uiView: UIActivityIndicatorView, context: Context) {
        if isAnimating {
            uiView.startAnimating()
        } else {
            uiView.stopAnimating()
        }
    }
}

Use it like any view: Spinner(isAnimating: isLoading). The two required methods have clear jobs:

  • makeUIView(context:) runs once when the view enters the hierarchy. Create the UIKit object here and set up everything that never changes.
  • updateUIView(_:context:) runs whenever SwiftUI state that the representable depends on changes, and once right after creation. Copy the new inputs into the UIKit view here.

The representable struct itself is thrown away and recreated like every SwiftUI view. The UIKit object it created is kept alive by SwiftUI between updates. That is why creation belongs in make and syncing in update.

Other pieces you may meet: dismantleUIView(_:coordinator:) for cleanup, sizeThatFits(_:uiView:context:) (iOS 16 and later) to take part in SwiftUI layout, and context.environment to read SwiftUI environment values such as the color scheme. For whole screens, UIViewControllerRepresentable works the same way with makeUIViewController and updateUIViewController; it is the route to system controllers such as a photo picker or the mail composer.

Coordinators: carrying delegate callbacks back

UIKit reports events through delegates: a UITextField calls textFieldDidChangeSelection, a picker calls didFinishPicking. Delegates must be class instances, but your representable is a struct that gets recreated. The solution is a coordinator, a class SwiftUI creates once through makeCoordinator() and keeps alive for as long as the UIKit view exists.

Swift
struct SearchField: UIViewRepresentable {
    @Binding var text: String

    func makeCoordinator() -> Coordinator {
        Coordinator(text: $text)
    }

    func makeUIView(context: Context) -> UITextField {
        let field = UITextField()
        field.placeholder = "Search"
        field.delegate = context.coordinator
        field.addTarget(
            context.coordinator,
            action: #selector(Coordinator.textChanged(_:)),
            for: .editingChanged
        )
        return field
    }

    func updateUIView(_ uiView: UITextField, context: Context) {
        if uiView.text != text {
            uiView.text = text
        }
        context.coordinator.text = $text
    }

    final class Coordinator: NSObject, UITextFieldDelegate {
        var text: Binding<String>

        init(text: Binding<String>) {
            self.text = text
        }

        @objc func textChanged(_ sender: UITextField) {
            text.wrappedValue = sender.text ?? ""
        }
    }
}

The data flows in a loop. SwiftUI to UIKit happens in updateUIView, which copies text into the field. UIKit to SwiftUI happens in the coordinator, which writes to the Binding when the user types. Two details prevent bugs:

  1. Guard the write in update. Setting uiView.text when it already equals the new value can reset the cursor or trigger the delegate again, which can start an update loop.
  2. Refresh the coordinator's binding in update, because it was created with the first binding and later copies may point to different state.

The first TryIt is a stand-in for this bridge in plain Swift. FakeTextField plays the UIKit object, Binding is a pair of closures like SwiftUI's, and the Coordinator forwards callbacks. Watch where each write happens.

Swift A representable, its coordinator and a binding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

After the user types, update() finds nothing to do. Without the equality check it would write the same text back to the field, which on a real UITextField can move the cursor or fire change events again.

The update loop problem

The second TryIt makes that risk concrete. It counts how many times the field is touched when update is careless and when it is careful, over a series of changes.

Swift Why update must be idempotent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Eight updates, but only three real changes. Do all updateUIView work as "make the UIKit object match the inputs", never as "perform an action".

UIHostingController: SwiftUI inside UIKit

The reverse bridge is simpler. UIHostingController is a UIViewController whose content is a SwiftUI view.

Swift
let profile = ProfileView(user: user)
let host = UIHostingController(rootView: profile)
navigationController?.pushViewController(host, animated: true)

To embed it in part of an existing screen, add it as a child view controller, which keeps UIKit's lifecycle callbacks correct:

Swift
let host = UIHostingController(rootView: BadgeView(count: 3))
addChild(host)
host.view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(host.view)
NSLayoutConstraint.activate([
    host.view.topAnchor.constraint(equalTo: view.topAnchor),
    host.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
    host.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
host.didMove(toParent: self)

To update the SwiftUI content later, assign host.rootView = BadgeView(count: 4) or give the view an observable model that both sides share (see @Observable). Table and collection view cells can host SwiftUI through UIHostingConfiguration (iOS 16), which lets you adopt SwiftUI for rows without rewriting the list. The hosting controller reports its size through sizeThatFits, so Auto Layout can place it, and sizingOptions controls how much it influences its parent.

Existing apps usually migrate in this direction: new screens in SwiftUI, hosted inside the UIKit navigation structure, while old screens stay as they are.

When to drop to UIKit

Choose SwiftUI first. Use UIKit through a representable when:

  • A framework only offers a UIKit surface, such as the camera preview layer, some document and picker controllers, or an SDK that ships a UIView.
  • You need control SwiftUI lacks, like very custom text editing, precise scroll offset control on older systems, or advanced collection view layouts.
  • Performance for a very large or exotic list has been measured (see performance and Instruments) and a collection view is demonstrably better.
  • You have a large UIKit codebase and are migrating screen by screen.
  • Your minimum iOS version lacks a SwiftUI feature that later versions provide natively.

Do not reach for UIKit out of habit. Every representable adds a coordinator, manual syncing, and two mental models. Newer SDKs keep adding SwiftUI-native replacements for things that once required UIKit, so check whether a native version exists for your minimum deployment target before wrapping.

Mixing state models safely

A few rules keep the bridge reliable:

  • Keep one source of truth, normally in SwiftUI, and pass it down as a value or Binding.
  • Never retain the representable struct itself in a UIKit object; retain the coordinator or the UIKit view.
  • Call UIKit on the main actor. Both protocols are main-actor isolated, but your own helper code might not be (see concurrency in iOS).
  • Avoid closures in the coordinator that capture the whole view strongly in a way that creates a retain cycle.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does makeUIView(context:) run?

    make creates the UIKit object once. SwiftUI keeps it and calls updateUIView whenever inputs change.
  2. 2. Why is a coordinator a class and not part of the representable struct?

    UIKit delegates are weak object references. The struct is recreated, so SwiftUI keeps one coordinator instance alive instead.
  3. 3. Which is the correct way to show a SwiftUI view in an existing UIKit screen?

    UIHostingController is the UIKit-side container for a SwiftUI view. UIViewRepresentable goes in the other direction.
  4. 4. Why should updateUIView compare values before writing to the UIKit view?

    update can run many times. Writing unchanged values may cause visible glitches or feedback loops.
  5. 5. Which situation is a good reason to use UIKit inside a SwiftUI app?

    Representables exist to wrap things that have no SwiftUI equivalent for your deployment target.

Summary

  • UIKit is imperative with long-lived reference-type views; SwiftUI is declarative with value-type descriptions. Interop reconciles the two.
  • UIViewRepresentable and UIViewControllerRepresentable wrap UIKit for SwiftUI: create in make, sync inputs in update, clean up in dismantle.
  • A Coordinator is a class created once by makeCoordinator(); it receives delegate and target-action callbacks and writes back through a Binding.
  • Keep update idempotent: compare before writing, and refresh the coordinator's binding.
  • UIHostingController embeds SwiftUI in UIKit, as a pushed screen or a child view controller; UIHostingConfiguration hosts SwiftUI in cells.
  • Default to SwiftUI and drop to UIKit only for missing features, SDK surfaces, measured performance needs or gradual migration.

Next: Testing View Models and UI.