Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
SwiftUI Cookbook - Third Edition

You're reading from  SwiftUI Cookbook - Third Edition

Product type Book
Published in Dec 2023
Publisher Packt
ISBN-13 9781805121732
Pages 798 pages
Edition 3rd Edition
Languages
Concepts
Author (1):
Juan C. Catalan Juan C. Catalan
Profile icon Juan C. Catalan

Table of Contents (20) Chapters

Preface 1. Using the Basic SwiftUI Views and Controls 2. Displaying Scrollable Content with Lists and Scroll Views 3. Exploring Advanced Components 4. Viewing while Building with SwiftUI Preview in Xcode 15 5. Creating New Components and Grouping Views with Container Views 6. Presenting Views Modally 7. Navigation Containers 8. Drawing with SwiftUI 9. Animating with SwiftUI 10. Driving SwiftUI with Data 11. Driving SwiftUI with Combine 12. SwiftUI Concurrency with async await 13. Handling Authentication and Firebase with SwiftUI 14. Persistence in SwiftUI with Core Data and SwiftData 15. Data Visualization with Swift Charts 16. Creating Multiplatform Apps with SwiftUI 17. SwiftUI Tips and Tricks 18. Other Books You May Enjoy
19. Index

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.

You have been reading a chapter from
SwiftUI Cookbook - Third Edition
Published in: Dec 2023 Publisher: Packt ISBN-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.
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 €14.99/month. Cancel anytime}