Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
SwiftUI Cookbook

You're reading from   SwiftUI Cookbook A guide for building beautiful and interactive SwiftUI apps

Arrow left icon
Product type Paperback
Published in Dec 2023
Publisher Packt
ISBN-13 9781805121732
Length 798 pages
Edition 3rd Edition
Languages
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Juan C. Catalan Juan C. Catalan
Author Profile Icon Juan C. Catalan
Juan C. Catalan
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Using the Basic SwiftUI Views and Controls FREE CHAPTER 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

Integrating UIKit into SwiftUI: the best of both worlds

SwiftUI was announced at WWDC 2019 and is only available on devices running iOS 13 and above. Many improvements and new APIs have been added to SwiftUI since its introduction, to the point that, at the time of this writing, we can create an app in SwiftUI without using any UIKit components.

However, if you’re dealing with legacy code written in UIKit, and have the need to integrate the code in your SwiftUI app, Apple provides a way to do this. UIViews and UIViewControllers can be seamlessly placed inside SwiftUI views and vice versa.

In this recipe, we’ll look at how to integrate UIKit APIs in SwiftUI. We will create a project that wraps instances of UIActivityIndicatorView to display an indicator in SwiftUI.

Getting ready

Open Xcode and create a SwiftUI project named UIKitToSwiftUI.

How to do it…

We can display UIKit views in SwiftUI by using the UIViewRepresentable protocol. Follow these steps to implement the UIActivityIndicatorView in SwiftUI:

  1. Within the Xcode menu, click File | New | File and select Swift File. Name the view ActivityIndicator.
  2. Replace the import Foundation statement with import SwiftUI:
    import SwiftUI
    
  3. Modify the code in ActivityIndicator to use the UIViewRepresentable protocol:
    struct ActivityIndicator: UIViewRepresentable {
         var animating: Bool
        
        func makeUIView(context: Context) ->
         UIActivityIndicatorView {
            return UIActivityIndicatorView()
        }
        
        func updateUIView(_ activityIndicator:
         UIActivityIndicatorView, context: Context) {
            if animating {
                activityIndicator.startAnimating()
            } else {
                activityIndicator.stopAnimating()
            }
        }
    }
    
  4. Let’s open the ContentView.swift file and replace the struct with the following code to make use of the ActivityIndicator instance that we just created. Let’s also add a Toggle control to turn the indicator on or off:
    struct ContentView: View {
        @State private var animate = true
        var body: some View {
            VStack{
                ActivityIndicator(animating:  animate)
                HStack{
                    Toggle(isOn: $animate){
                        Text("Toggle Activity")
                    }
                }.padding()
            }
        }
    }
    
  5. The resulting ContentView preview should look like this:

Figure 1.18: UIKit UIActivityIndicatorView inside our SwiftUI view

How it works…

UIKit views can be implemented in SwiftUI by using the UIViewRepresentable protocol to wrap the UIKit views. In this recipe, we make use of a UIActivityIndicatorView by first wrapping it with a UIViewRepresentable.

In our ActivityIndicator.swift file, we implement a struct that conforms to the UIViewRepresentable protocol. This requires us to implement both the makeUIView and updateUIView functions. The makeUIView function creates and prepares the view, while the updateUIView function updates the UIView when the animation changes.

Important Note

You can implement the preceding features in iOS 14+ apps by using SwiftUI’s ProgressView. The purpose of the recipe was to show how to integrate a UIKit view with SwiftUI.

See also

Check out the Exploring more views and controls recipe at the end of this chapter for more information on ProgressView.

Apple’s tutorial on how to integrate UIKit and SwiftUI:

https://developer.apple.com/tutorials/swiftui/interfacing-with-uikit

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 €18.99/month. Cancel anytime