Reader small image

You're reading from  SwiftUI Essentials – iOS 14 Edition

Product typeBook
Published inMay 2021
Reading LevelBeginner
PublisherPackt
ISBN-139781801813228
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

54. Integrating SwiftUI with UIKit

Apps developed before the introduction of SwiftUI will have been developed using UIKit and other UIKit-based frameworks included with the iOS SDK. Given the benefits of using SwiftUI for future development, it will be a common requirement to integrate the new SwiftUI app functionality with the existing project code base. Fortunately, this integration can be achieved with relative ease using the UIHostingController.

54.1 An Overview of the Hosting Controller

The hosting controller (in the form of the UIHostingController class) is a subclass of UIViewController, the sole purpose of which is to enclose a SwiftUI view so that it can be integrated into an existing UIKit-based project.

Using a hosting view controller, a SwiftUI view can be treated either as an entire scene (occupying the full screen), or as an individual component within an existing UIKit scene layout by embedding a hosting controller in a container view. A container view essentially allows a view controller to be configured as the child of another view controller.

SwiftUI views can be integrated into a UIKit project either from within the code or using an Interface Builder storyboard. The following code excerpt embeds a SwiftUI content view in a hosting view controller and then presents it to the user:

let swiftUIController =

                ...

54.2 A UIHostingController Example Project

Unlike previous chapters, the project created in this chapter will create a UIKit Storyboard-based project instead of a SwiftUI Multiplatform app. Launch Xcode and select the iOS tab followed by the App template as shown in Figure 54-1 below:

Figure 54-1

Click the Next button and, on the options screen, name the project HostingControllerDemo and change the Interface menu from SwiftUI to Storyboard. Click the Next button once again and proceed with the project creation process.

54.3 Adding the SwiftUI Content View

In the course of building this project, a SwiftUI content view will be integrated into a UIKit storyboard scene using the UIHostingController in three different ways. In preparation for this integration process, a SwiftUI View file needs to be added to the project. Add this file now by selecting the File -> New -> File… menu option and choosing the SwiftUI View template option from the resulting dialog. Proceed through the screens, keeping the default SwiftUIView file name.

With the SwiftUIView.swift file loaded into the editor, modify the declaration so that it reads as follows:

import SwiftUI

 

struct SwiftUIView: View {

    

    var text: String

    

    var body: some View {

        VStack {

            Text(text)

...

54.4 Preparing the Storyboard

Within Xcode, select the Main.storyboard file so that it loads into the Interface Builder tool. As currently configured, the storyboard consists of a single view controller scene as shown in Figure 54-2:

Figure 54-2

So that the user can navigate back to the current scene, the view controller needs to be embedded into a Navigation Controller. Select the current scene by clicking on the View Controller button circled in the figure above so that the scene highlights with a blue outline and select the Editor -> Embed In -> Navigation Controller menu option. At this point the storyboard canvas should resemble Figure 54-3:

Figure 54-3

The first SwiftUI integration will require a button which, when clicked, will show a new view controller containing the SwiftUI View. Display the Library panel by clicking on the button highlighted in Figure 54-4 and locate and drag a Button view onto the view controller scene canvas:

Figure 54...

54.5 Adding a Hosting Controller

The storyboard is now ready to add a UIHostingController and to implement a segue on the button to display the SwiftUIView layout. Display the Library panel once again, locate the Hosting View Controller and drag and drop it onto the storyboard canvas so that it resembles Figure 54-6 below:

Figure 54-6

Next, add the segue by selecting the “Show Second Screen” button and Ctrl-clicking and dragging to the Hosting Controller:

Figure 54-7

Release the line once it is within the bounds of the hosting controller and select Show from the resulting menu.

Compile and run the project on a simulator or connected device and verify that clicking the button navigates to the hosting controller screen and that the Navigation Controller has provided a back button to return to the initial screen. At this point the hosting view controller appears with a black background indicating that it currently has no content.

54.6 Configuring the Segue Action

The next step is to add an IBSegueAction to the segue that will load the SwiftUI view into the hosting controller when the button is clicked. Within Xcode, select the Editor -> Assistant menu option to display the Assistant Editor panel. When the Assistant Editor panel appears, make sure that it is displaying the content of the ViewController.swift file. By default, the Assistant Editor will be in Automatic mode, whereby it automatically attempts to display the correct source file based on the currently selected item in Interface Builder. If the correct file is not displayed, the toolbar along the top of the editor panel can be used to select the correct file.

If the ViewController.swift file is not loaded, begin by clicking on the Automatic entry in the editor toolbar as highlighted in Figure 54-8:

Figure 54-8

From the resulting menu (Figure 54-9), select the ViewController.swift file to load it into the editor:

Figure 54-9...

54.7 Embedding a Container View

For the second integration, a Container View will be added to an existing view controller scene and used to embed a SwiftUI view alongside UIKit components. Within the Main.storyboard file, display the Library and drag and drop a Container View onto the scene canvas of the initial view controller, then position and size the view so that it appears as shown in Figure 54-13:

Figure 54-13

Before proceeding, click on the background of the view controller scene before using the Resolve Auto Layout Issues button indicated in Figure 54-5 once again and select the Reset to Suggested Constraints option to add any missing constraints to the layout.

Note that Xcode has also added an extra View Controller for the Container View (located above the initial view controller in the above figure). This will need to be replaced by a Hosting Controller so select this controller and tap the keyboard delete key to remove it from the storyboard.

Display the...

54.8 Embedding SwiftUI in Code

In this, the final integration example, the SwiftUI view will be embedded into the layout for the initial view controller programmatically. Within Xcode, edit the ViewController.swift file, locate the viewDidLoad() method and modify it as follows:

override func viewDidLoad() {

    super.viewDidLoad()

    

    let swiftUIController = UIHostingController(rootView: SwiftUIView(text: "Integration Three"))

 

    addChild(swiftUIController)

    swiftUIController.view.translatesAutoresizingMaskIntoConstraints

                                                     ...

54.9 Summary

Any apps developed before the introduction of SwiftUI will have been created using UIKit. While it is certainly possible to continue using UIKit when enhancing and extending an existing app, it probably makes more sense to use SwiftUI when adding new app features (unless your app needs to run on devices that do not support iOS 13 or newer). Recognizing the need to integrate new SwiftUI-based views and functionality with existing UIKit code, Apple created the UIHostingViewController. This controller is designed to wrap SwiftUI views in a UIKit view controller that can be integrated into existing UIKit code. As demonstrated in this chapter, the hosting controller can be used to integrate SwiftUI and UIKit both within storyboards and programmatically within code. Options are available to integrate entire SwiftUI user interfaces in independent view controllers or, through the use of container views, to embed SwiftUI views alongside UIKit views within an existing layout.

...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
SwiftUI Essentials – iOS 14 Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801813228
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth