Book Image

SwiftUI Cookbook - Third Edition

By : Juan C. Catalan
5 (1)
Book Image

SwiftUI Cookbook - Third Edition

5 (1)
By: Juan C. Catalan

Overview of this book

SwiftUI is the modern way to build user interfaces for iOS, macOS, and watchOS. It provides a declarative and intuitive way to create beautiful and interactive user interfaces. The new edition of this comprehensive cookbook includes a fully updated repository for SwiftUI 5, iOS 17, Xcode 15, and Swift 5.9. With this arsenal, it teaches you everything you need to know to build beautiful and interactive user interfaces with SwiftUI 5, from the basics to advanced topics like custom modifiers, animations, and state management. In this new edition, you will dive into the world of creating powerful data visualizations with a new chapter on Swift Charts and how to seamlessly integrate charts into your SwiftUI apps. Further, you will be able to unleash your creativity with advanced controls, including multi-column tables and two-dimensional layouts. You can explore new modifiers for text, images, and shapes that give you more control over the appearance of your views. You will learn how to develop apps for multiple platforms, including iOS, macOS, watchOS, and more. With expert insights, real-world examples, and a recipe-based approach, you’ll be equipped to build remarkable SwiftUI apps that stand out in today’s competitive market.
Table of Contents (20 chapters)
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.