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

17. Using Xcode in SwiftUI Mode

When creating a new project, Xcode now provides a choice of creating either a Storyboard or SwiftUI based user interface for the project. When creating a SwiftUI project, Xcode appears and behaves significantly differently when designing the user interface for an app project compared to the UIKit Storyboard mode.

When working in SwiftUI mode, most of your time as an app developer will be spent in the code editor and preview canvas, both of which will be explored in detail in this chapter.

17.1 Starting Xcode 12

As with all the examples in this book, the development of our example will take place within the Xcode 12.2 development environment. If you have not already installed this tool together with the latest iOS SDK refer first to the “Installing Xcode 12 and the iOS 14 SDK” chapter of this book. Assuming the installation is complete, launch Xcode either by clicking on the icon on the dock (assuming you created one) or use the macOS Finder to locate Xcode in the Applications folder of your system.

When launched for the first time, and until you turn off the Show this window when Xcode launches toggle, the screen illustrated in Figure 17-1 will appear by default:

Figure 17-1

If you do not see this window, simply select the Window -> Welcome to Xcode menu option to display it. From within this window, click on the option to Create a new Xcode project.

17.2 Creating a SwiftUI Project

When creating a new project, the project template screen includes options to select how the app project is to be implemented. Options are available to design an app for a specific Apple platform (such as iOS, watchOS, macOS or tvOS), or to create a multiplatform project. Selecting a platform specific option will also provide the choice of creating either a Storyboard (UIKit) or SwiftUI based project.

A multiplatform project allows an app to be designed for multiple Apple platforms with the minimum of platform specific code. Even if you plan to initially only target iOS the multiplatform option is still recommended since it provides the flexibility to make the app available on other platforms in the future without having to restructure the project.

Templates are also available for creating a basic app, a document-based app or a game project. For the purposes of this chapter, use the multiplatform app option:

Figure 17-2

Clicking Next...

17.3 Xcode in SwiftUI Mode

Before beginning work on a SwiftUI user interface, it is worth taking some time to gain familiarity with how Xcode works in SwiftUI mode. A newly created multiplatform “app” project includes two SwiftUI View files named <app name>App.swift (in this case DemoProjectApp.swift) and ContentView.swift which, when selected from the project navigation panel, will appear within Xcode as shown in Figure 17-4 below:

Figure 17-4

Located to the right of the project navigator (A) is the code editor (B). To the right of this is the preview canvas (C) where any changes made to the SwiftUI layout declaration will appear in real-time.

Selecting a view in the canvas will automatically select and highlight the corresponding entry in the code editor, and vice versa. Attributes for the currently selected item will appear in the attributes inspector panel (D).

During debugging, the debug panel (E) will appear containing debug output from both...

17.4 The Preview Canvas

The preview canvas provides both a visual representation of the user interface design and a tool for adding and modifying views within the layout design. The canvas may also be used to perform live testing of the running app without the need to launch an iOS simulator. Figure 17-8 illustrates a typical preview canvas for a newly created project:

Figure 17-8

If the canvas is not visible it can be displayed using the Xcode Editor -> Canvas menu option.

The main canvas area (A) represents the current view as it will appear when running on a physical device. When changes are made to the code in the editor, those changes are reflected within the preview canvas. To avoid continually updating the canvas, and depending on the nature of the changes being made, the preview will occasionally pause live updates. When this happens, the Resume button will appear in the top right-hand corner of the preview panel which, when clicked, will once again begin updating...

17.5 Preview Pinning

When building an app in Xcode it is likely that it will consist of several SwiftUI View files in addition to the default ContentView.swift file. When a SwiftUI View file is selected from the project navigator, both the code editor and preview canvas will change to reflect the currently selected file. Sometimes you may want the user interface layout for one SwiftUI file to appear in the preview canvas while editing the code in a different file. This can be particularly useful if the layout from one file is dependent on or embedded in another view. The pin button (labeled C in Figure 17-8 above) pins the current preview to the canvas so that it remains visible on the canvas after navigating to a different view. The view to which you have navigated will appear beneath the pinned view in the canvas and can be scrolled into view.

17.6 The Preview Toolbar

The preview toolbar (marked D in Figure 17-8 above and shown below) provides a range of options for changing the preview panel:

Figure 17-10

By default, the preview displays a static representation of the user interface. To test the user interface in a running version of the app, simply click on the Live Preview button (A). Xcode will then build the app and run it within the preview canvas where you can interact with it as you would in a simulator or on a physical device. When in Live Preview mode, the button changes to a stop button which can be used to exit live mode.

The current version of the app may also be previewed on an attached physical device by clicking on the Preview on Device button (B). As with the preview canvas, the running app on the device will update dynamically as changes are made to the code in the editor.

The Inspect Preview button (C) displays the panel shown in Figure 17-11 below allowing properties of the canvas to...

17.7 Modifying the Design

Working with SwiftUI primarily involves adding additional views, customizing those views using modifiers, adding logic and interacting with state and other data instance bindings. All of these tasks can be performed exclusively by modifying the structure in the code editor. The font used to display the “Hello, world!” Text view, for example, can be changed by adding the appropriate modifier in the editor:

Text("Hello, world!")

    .padding()

    .font(.largeTitle)

An alternative to this is to make changes to the SwiftUI views by dragging and dropping items from the Library panel. The Library panel is displayed by clicking on the toolbar button highlighted in Figure 17-13:

Figure 17-13

When displayed, the Library panel will appear as shown in Figure 17-14:

Figure 17-14

When launched in this way, the Library panel is transient and will disappear either after a selection...

17.8 Editor Context Menu

Holding down the Command key while clicking on an item in the code editor will display the menu shown in Figure 17-18:

Figure 17-18

This menu provides a list of options which will vary depending on the type of item selected. Options typically include a shortcut to a popup version of the Attributes inspector for the current view, together with options to embed the current view in a stack or list container. This menu is also useful for extracting part of a view into its own self-contained subview. Creating subviews is strongly encouraged to promote reuse, improve performance and unclutter complex design structures.

17.9 Previewing on Multiple Device Configurations

Every newly created SwiftUI View file includes an additional declaration at the bottom of the file that resembles the following:

struct ContentView_Previews: PreviewProvider {

    static var previews: some View {

        ContentView()

    }

}

This structure, which conforms to the PreviewProvider protocol, returns an instance of the primary view within the file. This instructs Xcode to display the preview for that view within the preview canvas (without this declaration, nothing will appear in the canvas).

By default, the preview canvas shows the user interface on a single device based on the current selection in the run target menu to the right of the run and stop buttons in the Xcode toolbar (as highlighted in Figure 17-20 below). To preview on other device models, one option is to simply change the run target and wait for the preview...

17.10 Running the App on a Simulator

Although much can be achieved using the preview canvas, there is no substitute for running the app on physical devices and simulators during testing.

Within the main Xcode project window, the menu marked C in Figure 17-20 is used to choose a target simulator. This menu will include simulators which have been configured and any physical devices connected to the development system:

Figure 17-20

When a project is first created, it may initially be configured to target macOS instead of iOS as shown in Figure 17-21:

Figure 17-21

To switch to iOS, click on the area marked by the arrow above and select the iOS option from the resulting menu together with a device or simulator as illustrated below:

Figure 17-22

Clicking on the Run toolbar button (marked A in Figure 17-20 above) will compile the code and run the app on the selected target. The small panel in the center of the Xcode toolbar (D) will report the progress of...

17.11 Running the App on a Physical iOS Device

Although the Simulator environment provides a useful way to test an app on a variety of different iOS device models, it is important to also test on a physical iOS device.

If you have entered your Apple ID in the Xcode preferences screen as outlined in the Joining the Apple Developer Program chapter and selected a development team for the project, it is possible to run the app on a physical device simply by connecting it to the development Mac system with a USB cable and selecting it as the run target within Xcode.

With a device connected to the development system, and an application ready for testing, refer to the device menu located in the Xcode toolbar. There is a reasonable chance that this will have defaulted to one of the iOS Simulator configurations. Switch to the physical device by selecting this menu and changing it to the device name as shown in Figure 17-23:

Figure 17-23

With the target device selected, make...

17.12 Managing Devices and Simulators

Currently connected iOS devices and the simulators configured for use with Xcode can be viewed and managed using the Xcode Devices window which is accessed via the Window -> Devices and Simulators menu option. Figure 17-24, for example, shows a typical Device screen on a system where an iPhone has been detected:

Figure 17-24

A wide range of simulator configurations are set up within Xcode by default and can be viewed by selecting the Simulators button at the top of the left-hand panel. Other simulator configurations can be added by clicking on the + button located in the bottom left-hand corner of the window. Once selected, a dialog will appear allowing the simulator to be configured in terms of device model, iOS version and name.

17.13 Enabling Network Testing

In addition to testing an app on a physical device connected to the development system via a USB cable, Xcode also supports testing via a network connection. This option is enabled on a per device basis within the Devices and Simulators dialog introduced in the previous section. With the device connected via the USB cable, display this dialog, select the device from the list and enable the Connect via network option as highlighted in Figure 17-25:

Figure 17-25

Once the setting has been enabled, the device may continue to be used as the run target for the app even when the USB cable is disconnected. The only requirement being that both the device and development computer be connected to the same Wi-Fi network. Assuming this requirement has been met, clicking on the run button with the device selected in the run menu will install and launch the app over the network connection.

17.14 Dealing with Build Errors

If for any reason a build fails, the status window in the Xcode toolbar will report that an error has been detected by displaying “Build” together with the number of errors detected and any warnings. In addition, the left-hand panel of the Xcode window will update with a list of the errors. Selecting an error from this list will take you to the location in the code where corrective action needs to be taken.

17.15 Monitoring Application Performance

Another useful feature of Xcode is the ability to monitor the performance of an application while it is running, either on a device or simulator or within the Live Preview canvas. This information is accessed by displaying the Debug Navigator.

When Xcode is launched, the project navigator is displayed in the left-hand panel by default. Along the top of this panel is a bar with a range of other options. The seventh option from the left displays the debug navigator when selected as illustrated in Figure 17-26. When displayed, this panel shows a number of real-time statistics relating to the performance of the currently running application such as memory, CPU usage, disk access, energy efficiency, network activity and iCloud storage access.

Figure 17-26

When one of these categories is selected, the main panel (Figure 17-27) updates to provide additional information about that particular aspect of the application’s performance...

17.16 Exploring the User Interface Layout Hierarchy

Xcode also provides an option to break the user interface layout out into a rotatable 3D view that shows how the view hierarchy for a user interface is constructed. This can be particularly useful for identifying situations where one view instance is obscured by another appearing on top of it or a layout is not appearing as intended. This is also useful for learning how SwiftUI works behind the scenes to construct a SwiftUI layout, if only to appreciate how much work SwiftUI is saving us from having to do.

To access the view hierarchy in this mode, begin by previewing the view in debug mode as illustrated in Figure 17-12 above. Once the preview is live, click on the Debug View Hierarchy button indicated in Figure 17-28:

Figure 17-28

Once activated, a 3D “exploded” view of the layout will appear. Clicking and dragging within the view will rotate the hierarchy allowing the layers of views that make up the...

17.17 Summary

When creating a new project, Xcode provides the option to use either UIKit Storyboards or SwiftUI as the basis of the user interface of the app. When in SwiftUI mode, most of the work involved in developing an app takes place in the code editor and the preview canvas. New views can be added to the user interface layout and configured either by typing into the code editor or dragging and dropping components from the Library either onto the editor or the preview canvas.

The preview canvas will usually update in real time to reflect code changes as they are typed into the code editor, though will frequently pause updates in response to larger changes. When in the paused state, clicking the Resume button will restart updates. The Attribute inspector allows the properties of a selected view to be changed and new modifiers added. Holding down the Command key while clicking on a view in the editor or canvas displays the context menu containing a range of options such as...

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}