An iOS Developer's Guide to SwiftUI - Michele Fadda - E-Book

An iOS Developer's Guide to SwiftUI E-Book

Michele Fadda

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

– SwiftUI transforms Apple Platform app development with intuitive Swift code for seamless UI design.
– Explore SwiftUI's declarative programming: define what the app should look like and do, while the OS handles the heavy lifting.
– Hands-on approach covers SwiftUI fundamentals and often-omitted parts in introductory guides.
– Progress from creating views and modifiers to intricate, responsive UIs and advanced techniques for complex apps.
– Focus on new features in asynchronous programming and architecture patterns for efficient, modern app design.
– Learn UIKit and SwiftUI integration, plus how to run tests for SwiftUI applications.
– Gain confidence to harness SwiftUI's full potential for building professional-grade apps across Apple devices.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 486

Veröffentlichungsjahr: 2024

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



An iOS Developer’s Guide to SwiftUI

Design and build beautiful apps quickly and easily with minimum code

Michele Fadda

An iOS Developer’s Guide to SwiftUI

Copyright © 2024 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Rohit Rajkumar

Publishing Product Manager: Vaideeshwari Muralikrishnan

Book Project Manager: Aishwarya Mohan

Senior Editor: Rakhi Patel

Technical Editor: Reenish Kulshrestha

Copy Editor: Safis Editing

Indexer: Pratik Shirodkar

Production Designer: Prafulla Nikalje

DevRel Marketing Coordinators: Anamika Singh and Nivedita Pandey

First published: May 2024

Production reference: 1050424

Published by Packt Publishing Ltd.Grosvenor House 11 St Paul’s SquareBirmingham B3 1RB, UK

ISBN 978-1-80181-362-4

www.packtpub.com

Dedicated to my love, Stefania.

– Michele Giuseppe Fadda

Contributors

About the author

Michele Fadda is an Italian software developer with over 30 years of expertise in a range of sectors, including banking, healthcare, and open banking. He began his programming journey at 14 in Sassari and relocated to Milan in 1983, where he started his career in embedded systems software, later expanding into enterprise and mobile software development. Michele also contributed as a tech journalist from 1983 to 1997, focusing on digital electronics and programming. He is fluent in both Italian and English and holds an MBA from the Open University Business School, along with a diploma in business studies.

With a deep understanding of computing history, Michele has been at the forefront of software development since the Unix System V era. He has led IT projects for numerous Italian companies, mastering a variety of programming languages and, lately, specializing in iOS and Swift for mobile applications. Michele is particularly interested in cryptography and designing secure systems.

In addition to his professional achievements, Michele has a passion for electronic music, blending his technological expertise with a creative flair for sound. Since 2018, he has been working in the UK, working as an iOS developer. He is currently the CEO of FWLAB Limited and technical project and program manager at Eggon, an innovative Italian start-up.

I want to thank the Packt team and reviewers who helped me through this journey and made this book possible.

About the reviewer

Nimesh Neema is a passionate programmer who loves well-designed software. He is proficient with Apple developer technologies and has written apps for the iPhone, iPad, Mac, Apple Watch, and Apple TV. He has an excellent understanding of shell scripting, version control, and software engineering principles.

In a career spanning over 15 years, he has worked with teams of diverse sizes and backgrounds. He has experience writing utility, payment, gaming, hospitality, and low-level system apps.

He runs a software engineering consultancy, Perspicacious Solutions Private Limited, with clients from around the world. He engages in corporate training and speaking gigs. He is one of the highly-rated Apple development experts on codementor.io.

Table of Contents

Preface

Part 1: Simple Views

1

Exploring the Environment – Xcode, Playgrounds, and SwiftUI

Technical requirements

Exploring SwiftUI with Xcode

A brief tour of Xcode

Your first SwiftUI project

Creating a SwiftUI project

Creating a multi-platform project

Previews and the simulator

Playgrounds

The app submission process

Certificates

Mobile provisioning profiles

The application submission process

Summary

2

Adding Basic UI Elements and Designing Layouts

Technical requirements

Reusing views code

More about Text

Managing space in SwiftUI

The padding modifier

The .frame modifier

The .alignment modifier

The Spacer

The Divider

Digging deeper into stacks

Overview of stacks

HStack

ZStack

Summary

3

Adding Interactivity to a SwiftUI View

Technical requirements

Passing values at view creation

Responding to a button tap

Property wrappers

Limitations of @State

Changing a view appearance dynamically using modifiers

Bidirectional binding with Picker

Final notes on Subviews and @Binding, Classes, and @ObservableObject

Summary

Part 2: Scrollable Views

4

Iterating Views, Scroll Views, FocusState, Lists, and Scroll View Reader

Technical requirements

Iterating views

Hiding or showing the keyboard in a form using @FocusState

Scroll views

Controlling scrolling programmatically using ScrollViewReader

Summary

5

The Art of Displaying Grids

Technical requirements

Displaying grids in iOS

The Grid view

Creating a simple static grid

Lazy grids

Using GridItem to control the layout of LazyVGrid

Scrolling horizontally and sizing the grid automatically

Conditional formatting of a view

Reacting to device rotation

Summary

Part 3: SwiftUI Navigation

6

Tab Bars and Modal View Presentation

Technical requirements

Creating a standard tab bar

Creating custom tab bars

Adapting your code to different versions of the operating system

The hitchhiker’s guide to modal navigation

Showing a modal sheet

Showing alerts

The popover

Presentation detents

Summary

7

All About Navigation

Technical requirements

Navigation as a concept in iOS and other platforms

Showing a tab bar title with NavigationView

Presenting views with NavigationLink (pre-iOS 16)

Adding buttons to NavigationView and activating navigation programmatically

Using navigationDestination with NavigationStack

Using NavigationPath to control the navigation stack

NavigationSplitView – multicolumn navigation

Direct navigation stack manipulation with NavigationPath

Saving and loading the navigation stack

Summary

Part 4: Graphics and Animation

8

Creating Custom Graphics

Technical requirements

Creating custom modifiers

Drawing with the Canvas

Using CALayers in SwiftUI

Custom layout

Summary

9

An Introduction to Animations in SwiftUI

Technical requirements

Gestures

Basic gestures

Creating implicit animations

Explicit SwiftUI animations

Transitions

The .transition() modifier

The matchedGeometryEffect modifier

Summary

Part 5: App Architecture

10

App Architecture and SwiftUI Part I: Practical Tools

Diagrams

Dependency inversion

Clean Architecture

Different ways to decouple

Initializer injection

Method injection

Property injection

A matter of state

iOS 17 changes in state management

Other ways to chop your code

Summary

11

App Architecture and SwiftUI Part II – the Theory

Keeping it light enough

Conflict and the role of the architect

What good software architecture is and what it is not

Don’t be shy; ask an expert!

The origin of software patterns

Agency theory and bad architecture

Clean Architecture

TCA, The Composable Architecture

Summary

Part 6: Beyond Basics

12

Persistence with Core Data

What is persistency?

What is Core Data?

Understanding Core Data framework classes

Using Core Data with SwiftUI

Creating a Core Data project

Working with the data model file

Core Data migrations

The SQLite data file

CloudKit

Summary

13

Modern Structured Concurrency

A brief introduction to concurrency

Understanding traditional concurrency mechanisms

Threads

Callbacks and event loops

GCD

What is structured concurrency?

Using the async/await syntax

Understanding tasks

Task groups

Asynchronous streams

Actors

MainActor

Bridging old GCD and structured concurrency

Summary

14

An Introduction to SwiftData

Technical requirements

Understanding the differences between SwiftData and Core Data

SwiftData and SwiftUI

Exploring changes in the binding mechanisms

Creating a data model

Understanding relationships in SwiftData

One-to-one relationships

One-to-many relationships

Many-to-one relationships

Many-to-many relationships

Cascading deletion rules

Fetching data

Filtering data with predicates

Summary

15

Consuming REST Services in SwiftUI

Technical requirements

An overview of REST

Ports

Understanding REST requests in Swift

Codable, Encodable, and Decodable protocols

Using URLSession

Implementing HTTP methods

Setting headers

Handling errors

URLProtocol

Summary

16

Exploring the Apple Vision Pro

Technical requirements

Tools for visionOS development

An overview of Unity and RealityKit

First steps with visionOS development

Summary

Index

Other Books You May Enjoy

Preface

This book teaches you about SwiftUI, a multiplatform declarative user interface framework that can be used to program all Apple devices, currently including Mac, iPhone, iPad, Apple TV, Apple Watch, and Vision Pro.

Who this book is for

This book is aimed at iOS developers who want to expand their knowledge of adding SwiftUI to their bag of tools and want to progress further in their professional careers.

What this book covers

Chapter 1, Exploring the Environment – Xcode, Playgrounds, and SwiftUI, is an introduction to the software tools used when working with SwiftUI, the new exciting, efficient, and simple-to-use Apple framework for user interfaces.

Chapter 2, Adding Basic UI Elements and Designing Layouts, shows you how to properly refactor view code. Then, it describes how to combine basic views with stacks and control their visual layout.

Chapter 3, Adding Interactivity to a SwiftUI View, discusses the conversion from static to dynamic SwiftUI views, with a focus on responsive design, including taps and gestures. This chapter explores mechanisms to enable views to be made interactive. It covers topics such as view creation, interactivity enhancement, property wrappers, limitations of @State, bidirectional bindings, subviews, and the use of @ObservableObject and @StateObject classes.

Chapter 4, Iterating Views, Scroll Views, FocusState, Lists, and Scroll View Reader, focuses on showing lists in SwiftUI, through scrollable views such as scroll views or lists. It shows how to handle the visibility of the iOS system keyboard. It introduces NavigationView for view titles and covers iterating views, @ViewBuilder, scroll views, @FocusState for keyboard control, lists, and ScrollViewReader for element positioning within lists or scroll views.

Chapter 5, The Art of Displaying Grids, moves on to creating grid structures in SwiftUI. Topics covered include displaying grids in iOS, the grid view, lazy grids, using GridItem for layout control, conditional view formatting, and responding design to device orientation changes.

Chapter 6, Tab Bars and Modal View Presentation, focuses on using tab bars and modal view presentations in SwiftUI. It begins with the TabView, which is the most common way of moving between views in a small-scale iOS app. Topics covered include how to add a tab bar using TabView and tabItem, implementing custom tab bars, and an exhaustive investigation into modal views such as sheets, alerts, and popovers.

Chapter 7, All About Navigation, introduces the concept of navigation in SwiftUI. It starts with an overview of iOS navigation and then deals with programmatic and user-initiated navigation. It illustrates the changes with Swift 4 and iOS 16. Topics discussed are navigation across platforms, basic navigation with NavigationView and NavigationLink, .navigationDestination, user-controlled and split view navigation, programmatic navigation with NavigationPath, and saving/restoring the navigation stack in the JSON format.

Chapter 8, Creating Custom Graphics, shows you how to style apps by creating custom modifiers, diving into the use of core graphics inside the Canvas view, CALayers integration with SwiftUI. Then, the chapter goes further, illustrating how to use CustomLayout.

Chapter 9, An Introduction to Animations in SwiftUI, highlights SwiftUI animations, explaining their state-driven, reactive nature, made possible by SwiftUI’s declarative syntax. It explains the built-in modifiers of animation, transition, and scaleEffect.

Chapter 10, App Architecture and SwiftUI Part I – the Practical Tools, dissects the impact that SwiftUI has had in restructuring the application architecture on Apple’s operating systems. It introduces conceptual tools that allow a developer to segment an app into manageable components. This chapter focuses on ad hoc architecture rather than offering a one-size-fits-all solution. Key topics include diagrams, dependency inversion, clean architecture, decoupling techniques, state management, and iOS 17 changes on state bindings.

Chapter 11, App Architecture and SwiftUI Part II – the Theory, introduces modern application architecture, taking note of the specificity of the iOS context. It explains the concept of software architecture to give a theoretical understanding and criteria for evaluating well-designed architecture. Key topics include the principles of lightweight architecture, conflict resolution, defining good architecture, the importance of software patterns, the role of the architect, consulting experts, the difference between full-scale applications and examples, and the impact of Conway’s law.

Chapter 12, Persistence with Core Data, focuses on defining persistence, explaining Core Data’s structure, its integration with SwiftUI, and its practical use in Xcode. It touches on CloudKit for cloud-based data storage. Key topics include the Core Data’s framework classes, Core Data with SwiftUI, project creation and migrations, the SQLite data file, and CloudKit.

Chapter 13, Modern Structured Concurrency, discusses concurrency in mobile application development nowadays, applied specifically to Swift. The chapter outlines the history of concurrency from traditional mechanisms, such as threads and callbacks, to Apple’s modern structured concurrency approach. Its topics include async/await, tasks, task groups, asynchronous sequences and streams, actors, and integrating old-fashioned concurrency with modern structured concurrency.

Chapter 14, An Introduction to SwiftData, describes Apple’s ORM (Object Relational Mapping) framework, SwiftData, which is set to replace Core Data in SwiftUI development. The topics covered include SwiftData versus Core Data, SwiftData’s features, SwiftUI integration, data modeling, and the changes in binding.

Chapter 15, Consuming REST services in SwiftUI, explains HTTP, and REST as concepts and how to integrate REST services into SwiftUI applications for iOS apps that demand communication over the internet. Topics covered include HTTP requests made using URLSession, converting to and from JSON using Codable, watching UI changes with ObservableObject and @Published, avoiding man-in-the-middle attacks, and handling network errors.

Chapter 16, Exploring the Apple Vision Pro, introduces Apple Vision Pro, an advanced mixed-reality headset, and its importance for spatial computing. It describes the device’s immersive three-dimensional interface. It also goes into the development tools for visionOS, starting development with visionOS, and the initial steps in visionOS development.

To get the most out of this book

It is assumed that you will be familiar with basic computer science and programming in the Swift programming language on Apple devices.

Software/hardware covered in the book

Operating system requirements

macOS

A recent macOS Version, at least Sonoma (14.2.1 or later), in order to follow examples based on Xcode 15.2 for the last chapters.

Xcode

Most examples will run on Xcode 14.3 or later except when indicated at the beginning of the chapter.

The chapters on SwiftData and visionOS require Xcode 15.2 or later.

Physical devices

You can follow the examples for iOS and iPadOS by using the simulator; you don’t need physical devices for learning.

To run the code in this book on macOS, you will need macOS 14.2.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

You will need a developer’s account only if you want to use physical devices. Xcode can be downloaded for free from the Mac App Store and won’t require a developer’s account in order to run your own applications on the simulator.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/An-iOS-Developer-s-Guide-to-SwiftUI. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “In order to create explicit animations, you use the .animation(_: value:) modifier rather than the simpler .withAnimation closure.”

A block of code is set as follows:

// if you are using Xcode 14.x you will need this syntax for the preview functionality: struct ContentView_Previews: PreviewProvider {     static var previews: some View {         ContentView()     }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

[default] // if you are using Xcode 15 or later, the preview can be simplified as follows: #Preview {  ContentView()}

Any command-line input or output is written as follows:

$ cd projectFolder $ open .

Bold: Indicates a new term, an important word, or words that you see on screen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Select Settings from the Xcode menu.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read An iOS Developer’s Guide to SwiftUI, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your e-book purchase not compatible with the device of your choice?

Don’t worry!, Now with every Packt book, you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the following link:

https://packt.link/free-ebook/9781801813624

Submit your proof of purchase.That’s it! We’ll send your free PDF and other benefits to your email directly.

Part 1: Simple Views

In this part, you will be introduced to SwiftUI, the multiplatform UI framework from Apple that allows developers to build user interfaces for all Apple devices. These chapters have been designed for iOS developers in such a way that they guide you through the main concepts of SwiftUI and its practical implementation, offering a concrete base to develop powerful and visually beautiful applications.

You will start to explore the fundamentals of SwiftUI and its declarative syntax to build an intuitive and efficient UI. We’ll cover key concepts, such as views, modifiers, and state management, demonstrating how these components work together to build dynamic layouts.

You will learn to manage data well within SwiftUI, ensuring slick, dynamic user interfaces are produced through bindings, observable objects, and environment values.

This part will teach you how to work with animation and the gesture features of SwiftUI by applying them with a layer of polish and interactivity to your apps. You should reach the end of this section prepared with the knowledge and skills needed to begin using SwiftUI for your iOS development projects, making applications that are not only functional but also visually engaging.

This part contains the following chapters:

Chapter 1, Exploring the Environment – Xcode, Playgrounds, and SwiftUIChapter 2, Adding Basic UI Elements and Designing LayoutsChapter 3, Adding Interactivity to a SwiftUI View