Bridging the Gap: Integrating SwiftUI with UIKit Using UIHostingController

SwiftUI UIHostingController

Posted on 09 Jul 2024 . 3 min read


Introduction


With the introduction of SwiftUI, Apple has provided developers with a modern way to build user interfaces across all Apple platforms. However, many apps are still built using UIKit, and a complete rewrite might not be feasible. This is where UIHostingController comes into play, acting as a bridge that allows you to integrate SwiftUI views into your existing UIKit apps seamlessly. In this blog post, we’ll explore how to use UIHostingController to marry the old with the new.


What is UIHostingController?


UIHostingController is a class provided by Apple that allows you to embed SwiftUI views within a UIKit-based application. This enables developers to gradually adopt SwiftUI in their existing projects or add SwiftUI views to specific parts of their UIKit apps.


Key Features of UIHostingController


  • Initialization: You can initialize UIHostingController with any SwiftUI view.
  • Integration with UIKit: Easily present or add the hosting controller to your view hierarchy.
  • Updating Views: Dynamically update the SwiftUI view being displayed.
  • Layout Management: Adhere to UIKit’s layout constraints seamlessly.


Step-by-Step Guide


1. Creating a Simple SwiftUI View


First, let’s create a simple SwiftUI view. This view will be embedded in our UIKit-based application.


import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, SwiftUI!")
            .padding()
    }
}


2. Integrating SwiftUI View into UIKit


Now, we’ll integrate this SwiftUI view into a UIKit view controller using UIHostingController.


        
import SwiftUI
import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // Create a UIHostingController with the SwiftUI view
        let contentView = ContentView()
        let hostingController = UIHostingController(rootView: contentView)

        // Add the hosting controller as a child view controller
        addChild(hostingController)
        view.addSubview(hostingController.view)
        
        // Set up the constraints
        hostingController.view.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
            hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor)
        ])

        // Notify the hosting controller that it has been moved to a parent
        hostingController.didMove(toParent: self)
    }
}
    


3. Presenting SwiftUI View Modally


Another common scenario is presenting a SwiftUI view modally from a UIKit view controller.


let swiftUIView = ContentView()
let hostingController = UIHostingController(rootView: swiftUIView)
present(hostingController, animated: true, completion: nil)


4. Updating the SwiftUI View


You can also dynamically update the SwiftUI view displayed by the UIHostingController.


hostingController.rootView = AnotherSwiftUIView()


Benefits of Using UIHostingController


  • Gradual Adoption: Integrate SwiftUI incrementally without a complete rewrite.
  • Flexibility: Use the best of both SwiftUI and UIKit as per the needs of your project.
  • Modern UI: Leverage SwiftUI’s declarative syntax and powerful UI components in existing projects.


The bottom line


UIHostingController offers a powerful way to integrate SwiftUI views within UIKit applications, providing a flexible path for developers to adopt SwiftUI incrementally. Whether you are looking to modernize certain parts of your app or gradually transition to SwiftUI, UIHostingController is an invaluable tool. Start experimenting with it today and enjoy the best of both worlds!


Additional Resources


By understanding and utilizing UIHostingController, you can effectively bridge the gap between UIKit and SwiftUI, leveraging the strengths of both frameworks to create compelling, modern applications.


Don’t hesitate to contact me if you have any questions or queries. Follow me on twitter @gurjitpt for any updates.


Thanks!


Share this article



Written By

Generic placeholder image

Gurjit Singh

I’m Computer Science graduate and an iOS Engineer who writes about Swift and iOS development. Follow me for more updates:


Discover articles by topics

SwiftUI Class Struct Networking XCode NSCache Enum Optionals Property Observers Closures Guard Reviews StoreKit App Store Algorithms Testing Operators Protocol Extensions Weak Unowned SwiftData WWDC23 GCD API Admob SwiftLint Lottie Foreach Objective-C UIKit NavigationSplitView

Related Articles


String Concatenation in Swift: A Comprehensive Guide

In any programming language, working with strings is essential, and Swift is no different.Whether you are building iOS apps......

2024-10-17 . 3 min read     String Concatenation

Read More »

Integrating SwiftUI with UIKit Using UIHostingController

With the introduction of SwiftUI, Apple has provided developers with a modern way to build user interfaces across all Apple platforms....

2024-07-09 . 3 min read     UIHostingController

Read More »

Deep Dive into Autorelease Pools in Swift

In the realm of software development, memory management plays a crucial role in ensuring the efficient allocation and deallocation of memory...

2024-01-28 . 4 min read     Swift Autorelease

Read More »

How to create Date Picker in SwiftUI

Use a DatePicker when creating a view that enables users to choose both a calendar date and, if needed, a specific time.In SwiftUI, you can ...

2024-01-16 . 2 min read     SwiftUI DatePicker

Read More »

Getting started with Swiftlint to enforce Swift style

SwiftLint is a tool that ensures Swift code adheres to defined style guidelines. It automates code review by identifying and suggesting impr...

2023-12-29 . 4 min read     Swift SwiftLint

Read More »

How to use Lottie animation in SwiftUI

Lottie is a fantastic tool for incorporating high-quality animations into your SwiftUI projects. There are several ways to add Lottie to pro...

2023-12-13 . 2 min read     SwiftUI Lottie

Read More »