Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
SwiftUI Essentials – iOS 14 Edition

You're reading from  SwiftUI Essentials – iOS 14 Edition

Product type Book
Published in May 2021
Publisher Packt
ISBN-13 9781801813228
Pages 494 pages
Edition 1st Edition
Languages
Author (1):
Neil Smyth Neil Smyth
Profile icon Neil Smyth

Table of Contents (56) Chapters

1. Start Here 2. Joining the Apple Developer Program 3. Installing Xcode 12 and the iOS 14 SDK 4. An Introduction to Xcode 12 Playgrounds 5. Swift Data Types, Constants and Variables 6. Swift Operators and Expressions 7. Swift Control Flow 8. The Swift Switch Statement 9. Swift Functions, Methods and Closures 10. The Basics of Swift Object-Oriented Programming 11. An Introduction to Swift Subclassing and Extensions 12. An Introduction to Swift Structures and Enumerations 13. An Introduction to Swift Property Wrappers 14. Working with Array and Dictionary Collections in Swift 15. Understanding Error Handling in Swift 5 16. An Overview of SwiftUI 17. Using Xcode in SwiftUI Mode 18. SwiftUI Architecture 19. The Anatomy of a Basic SwiftUI Project 20. Creating Custom Views with SwiftUI 21. SwiftUI Stacks and Frames 22. SwiftUI State Properties, Observable, State and Environment Objects 23. A SwiftUI Example Tutorial 24. SwiftUI Lifecycle Event Modifiers 25. SwiftUI Observable and Environment Objects – A Tutorial 26. SwiftUI Data Persistence using AppStorage and SceneStorage 27. SwiftUI Stack Alignment and Alignment Guides 28. SwiftUI Lists and Navigation 29. A SwiftUI List and Navigation Tutorial 30. An Overview of List, OutlineGroup and DisclosureGroup 31. A SwiftUI List, OutlineGroup and DisclosureGroup Tutorial 32. Building SwiftUI Grids with LazyVGrid and LazyHGrid 33. Building Tabbed and Paged Views in SwiftUI 34. Building Context Menus in SwiftUI 35. Basic SwiftUI Graphics Drawing 36. SwiftUI Animation and Transitions 37. Working with Gesture Recognizers in SwiftUI 38. Creating a Customized SwiftUI ProgressView 39. An Overview of SwiftUI DocumentGroup Scenes 40. A SwiftUI DocumentGroup Tutorial 41. An Introduction to SiriKit 42. A SwiftUI SiriKit Messaging Extension Tutorial 43. Customizing the SiriKit Intent User Interface 44. A SwiftUI SiriKit NSUserActivity Tutorial 45. An Overview of Siri Shortcut App Integration 46. A SwiftUI Siri Shortcut Tutorial 47. Building Widgets with SwiftUI and WidgetKit 48. A SwiftUI WidgetKit Tutorial 49. Supporting WidgetKit Size Families 50. A SwiftUI WidgetKit Deep Link Tutorial 51. Adding Configuration Options to a WidgetKit Widget 52. Integrating UIViews with SwiftUI 53. Integrating UIViewControllers with SwiftUI 54. Integrating SwiftUI with UIKit 55. Preparing and Submitting an iOS 14 Application to the App Store Index

52. Integrating UIViews with SwiftUI

Prior to the introduction of SwiftUI, all iOS apps were developed using UIKit together with a collection of UIKit-based supporting frameworks. Although SwiftUI is provided with a wide selection of components with which to build an app, there are instances where there is no SwiftUI equivalent to options provided by the other frameworks.

Given the quantity of apps that were developed before the introduction of SwiftUI it is also important to be able to integrate existing non-SwiftUI functionality with SwiftUI development projects and vice versa. Fortunately, SwiftUI includes several options to perform this type of integration.

52.1 SwiftUI and UIKit Integration

Before looking in detail at integrating SwiftUI and UIKit it is worth taking some time to explore whether a new app project should be started as a UIKit or SwiftUI project, and whether an existing app should be migrated entirely to SwiftUI. When making this decision, it is important to remember that apps containing SwiftUI code can only be used on devices running iOS 13 or later.

If you are starting a new project, then the best approach may be to build it as a SwiftUI project (support for older iOS versions not withstanding) and then integrate with UIKit when required functionality is not provided directly by SwiftUI. Although Apple continues to enhance and support the UIKit way of developing apps, it is clear that Apple sees SwiftUI as the future of app development. SwiftUI also makes it easier to develop and deploy apps for iOS, macOS, tvOS, iPadOS and watchOS without making major code changes.

If, on the other hand, you have existing projects...

52.2 Integrating UIViews into SwiftUI

The individual components that make up the user interface of a UIKit-based application are derived from the UIView class. Buttons, labels, text views, maps, sliders and drawings (to name a few) are all ultimately subclasses of the UIKit UIView class.

To facilitate the integration of a UIView based component into a SwiftUI view declaration, SwiftUI provides the UIViewRepresentable protocol. To integrate a UIView component into SwiftUI, that component needs to be wrapped in a structure that implements this protocol.

At a minimum the wrapper structure must implement the following methods to comply with the UIViewRepresentable protocol:

makeUIView() – This method is responsible for creating an instance of the UIView-based component, performing any necessary initialization and returning it.

updateView() – Called each time a change occurs within the containing SwiftUI view that requires the UIView to update...

52.3 Adding a Coordinator

A coordinator takes the form of a class that implements the protocols and handler methods required by the wrapped UIView component to handle events. An instance of this class is then applied to the wrapper via the makeCoordinator() method of the UIViewRepresentable protocol.

As an example, consider the UIScrollView class. This class has a feature whereby a refresh control (UIRefreshControl) may be added such that when the user attempts to scroll beyond the top of the view, a spinning progress indicator appears and a method called allowing the view to be updated with the latest content. This is a common feature used by news apps to allow the user to download the latest news headlines. Once the refresh is complete, this method needs to call the endRefreshing() method of the UIRefreshControl instance to remove the progress spinner.

Clearly, if the UIScrollView is to be used with SwiftUI, there needs to be a way for the view to be notified that the UIRefreshControl...

52.4 Handling UIKit Delegation and Data Sources

Delegation is a feature of UIKit that allows an object to pass the responsibility for performing one or more tasks on to another object and is another area in which extra steps may be necessary if events are to be handled by a wrapped UIView.

The UIScrolledView, for example, can be assigned a delegate which will be notified when certain events take place such as the user performing a scrolling motion or when the user scrolls to the top of the content. The delegate object will need to conform to the UIScrolledViewDelegate protocol and implement the specific methods that will be called automatically when corresponding events take place in the scrolled view.

Similarly, a data source is an object which provides a UIView based component with data to be displayed. The UITableView class, for example, can be assigned a data source object to provide the cells to be displayed in the table. This data object must conform with the UITableViewDataSource...

52.5 An Example Project

The remainder of this chapter will work through the creation of a simple project that demonstrates the use of the UIViewRepresentable protocol to integrate a UIScrolledView into a SwiftUI project.

Begin by launching Xcode and creating a new SwiftUI Multiplatform App project named UIViewDemo.

52.6 Wrapping the UIScrolledView

The first step in the project is to use the UIViewRepresentable protocol to wrap the UIScrollView so that it can be used with SwiftUI. Right-click on the Shared folder entry in the project navigator panel, select the New File… menu option and create a new file named MyScrollView using the SwiftUI View template.

With the new file loaded into the editor, delete the current content and modify it so it reads as follows:

import SwiftUI

 

struct MyScrollView: UIViewRepresentable {

    

    var text: String

    

    func makeUIView(context: UIViewRepresentableContext<MyScrollView>)

               -> UIScrollView {

        let scrollView = UIScrollView()

        scrollView...

52.7 Implementing the Coordinator

Remaining within the MyScrollView.swift file, add the coordinator class declaration so that it reads as follows:

struct MyScrollView: UIViewRepresentable {

.

.

    func updateUIView(_ uiView: UIScrollView, context: UIViewRepresentableContext<MyScrollView>) {

    

    }

 

    class Coordinator: NSObject, UIScrollViewDelegate {

        var control: MyScrollView

 

        init(_ control: MyScrollView) {

            self.control = control

        }

        

        func scrollViewDidScroll(_ scrollView: UIScrollView) {

      ...

52.8 Using MyScrollView

The final step in this example is to check that MyScrollView can be used from within SwiftUI. To achieve this, load the ContentView.swift file into the editor and modify it so that it reads as follows:

.

.

struct ContentView: View {

    var body: some View {

        MyScrollView(text: "UIView in SwiftUI")

    }

}

.

.

Use Live Preview to test that the view works as expected.

52.9 Summary

SwiftUI includes several options for integrating with UIKit-based views and code. This chapter has focused on integrating UIKit views into SwiftUI. This integration is achieved by wrapping the UIView instance in a structure that conforms to the UIViewRepresentable protocol and implementing the makeUIView() and updateView() methods to initialize and manage the view while it is embedded in a SwiftUI layout. For UIKit objects that require a delegate or data source, a Coordinator class needs to be added to the wrapper and assigned to the view via a call to the makeCoordinator() method.

lock icon The rest of the chapter is locked
You have been reading a chapter from
SwiftUI Essentials – iOS 14 Edition
Published in: May 2021 Publisher: Packt ISBN-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.
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}