Reader small image

You're reading from  SwiftUI Cookbook - Third Edition

Product typeBook
Published inDec 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781805121732
Edition3rd Edition
Languages
Tools
Concepts
Right arrow
Author (1)
Juan C. Catalan
Juan C. Catalan
author image
Juan C. Catalan

Juan C. Catalan is a software engineer with more than 18 years of professional experience. He started mobile development back in the days of iOS 3. Juan has worked as a professional iOS developer in many industries, including medical devices, financial services, real estate, document management, fleet tracking and industrial automation. He has contributed to more than 30 published apps in the App Store, some of them with millions of users. Juan gives back to the iOS development community with technical talks, mentoring developers, reviewing technical books and now as a book author. He lives in Austin, Texas, with his wife Donna, where they spend time with their kids.
Read more about Juan C. Catalan

Right arrow

Adding SwiftUI to a legacy UIKit app

In this recipe, we will learn how to navigate from a UIKit view to a SwiftUI view while passing a secret text to our SwiftUI view. This recipe assumes prior knowledge of UIKit and it is most useful to developers who want to integrate SwiftUI into a legacy UIKit app. If this is not your case, feel free to skip to the next recipe.

We’ll be making use of a UIKit storyboard, a visual representation of the UI in UIKit. The Main.storyboard file is to UIKit what the ContentView.swift file is to SwiftUI. They are both the default home views that are created when you start a new project.

We start off this project with a simple UIKit project that contains a button.

Getting ready

Get the following ready before starting out with this recipe:

  1. Clone or download the code for this book from GitHub: https://github.com/PacktPublishing/SwiftUI-Cookbook-3rd-Edition/tree/main/Chapter01-Using-the-basic-SwiftUI-Views-and-Controls/10-Adding-SwiftUI-to-UIKit.
  2. Open the StartingPoint folder and double-click on AddSwiftUIToUIKit.xcodeproj to open the project in Xcode.

How to do it…

We will add a NavigationController to the UIKit ViewController that allows the app to switch from the UIKit to the SwiftUI view when the button is clicked:

  1. Open the Main.storyboard file in Xcode by clicking on it. The Main.storyboard looks like this:

Figure 1.19: UIKit View Controller

  1. Click anywhere in the ViewController to select it.
  2. In the Xcode menu, click Editor | Embed in | Navigation Controller.
  3. Add a new ViewController to the project:
    1. Click the + button at the top right of the Xcode window.
    2. In the new window, select the Objects library, type hosting in the search bar, select Hosting View Controller, and drag it out to the storyboard:

Figure 1.20: Creating a UIKit Hosting View Controller

  1. Hold down the Ctrl key, and then click and drag from the ViewController button to the new Hosting View Controller that we added.
  2. In the pop-up menu, for the Action Segue option, select Show.
  3. Click the Adjust Editor Options button:
Figure 1.21 – Adjust Editor Options button

Figure 1.21: Adjust Editor Options button

  1. Click Assistant. This splits the view into two panes, as shown here:

Figure 1.22: Xcode with the Assistant editor open

  1. To create a segue action, hold the Ctrl key, then click and drag from the segue button (item in the middle of the blue arrow in Figure 1.22) to the space after the viewDidLoad function in the ViewController.swift file.
  2. In the pop-up menu, enter the name goToSwiftUI and click Connect. The following code will be added to the ViewController.swift file:
        @IBSegueAction func goToSwiftUI(_ coder: NSCoder) -> UIViewController? {
            return <#UIHostingController(coder: coder, rootView: ...)#>
        }
    
  3. Add a statement to import SwiftUI at the top of the ViewController page, below import UIKit:
    import SwiftUI
    
  4. Within the goToSwiftUI function, create a text that will be passed to our SwiftUI view. Also, create a rootView variable that specifies the SwiftUI view that you would like to reach. Finally, return the UIHostingController, which is a special ViewController used to display the SwiftUI view. The resulting code should look like this:
        @IBSegueAction func goToSwiftUI(_ coder: NSCoder) -> UIViewController? {
            let greetings = "Hello From UIKit"
            let rootView = Greetings(textFromUIKit: greetings)
            return UIHostingController(coder: coder, rootView: rootView)
        }
    
  5. At this point, the code will not compile because we have not yet implemented a Greetings view. Let’s resolve that now.
  6. Create a SwiftUI view to display a message:
    1. Click File | New | File and select SwiftUI View.
    2. Name the view Greetings.swift.
  7. Add a View component that displays some text passed to it:
    struct Greetings: View {
        var textFromUIKit: String
        var body: some View {
            Text(textFromUIKit)
        }
    }
    #Preview {
        Greetings(textFromUIKit: "Hello, World!")
    }
    

Run the project in the simulator, click on the UIKit button, and watch the SwiftUI page get displayed.

How it works…

To host SwiftUI views in an existing app, you need to wrap the SwiftUI hierarchy in a ViewController or InterfaceController.

We start by performing core UIKit concepts, such as adding a Navigation View Controller to the storyboard and adding a Hosting View Controller as a placeholder for our SwiftUI view.

Lastly, we create an IBSegueAction to present our SwiftUI view upon clicking the UIKit button.

Previous PageNext Page
You have been reading a chapter from
SwiftUI Cookbook - Third Edition
Published in: Dec 2023Publisher: PacktISBN-13: 9781805121732
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 $15.99/month. Cancel anytime

Author (1)

author image
Juan C. Catalan

Juan C. Catalan is a software engineer with more than 18 years of professional experience. He started mobile development back in the days of iOS 3. Juan has worked as a professional iOS developer in many industries, including medical devices, financial services, real estate, document management, fleet tracking and industrial automation. He has contributed to more than 30 published apps in the App Store, some of them with millions of users. Juan gives back to the iOS development community with technical talks, mentoring developers, reviewing technical books and now as a book author. He lives in Austin, Texas, with his wife Donna, where they spend time with their kids.
Read more about Juan C. Catalan