Share E-Book

An iOS Developers Guide to SwiftUI Design and build beautiful apps quickly and easily with minimum code (Michele Fadda)(Z-Library)

Author Michele Fadda

code
Language English

Get started with SwiftUI and build efficient iOS apps in this illustrated, easy-to-follow guide with coverage on integration with UIKit, asynchronous programming techniques, efficient app architecture and design patterns Features Learn how to structure and maintain clean app architecture Under the guidance of industry expert Michele Fadda, build well-structured, maintainable, and high-performance applications Understand the declarative functional approach and focus on asynchronous programming within the context of SwiftUI What you will learn Get to grips with UI coding across Apple platforms using SwiftUI Build modern apps, delving into complex architecture and asynchronous programming Explore animations, graphics, and user gestures to build responsive UIs Respond to asynchronous events and store and share data the modern way Add advanced features by integrating SwiftUI and UIKit to enhance your apps Gain proficiency in testing and debugging SwiftUI applications Who this book is for This book is for iOS developers interested in mastering SwiftUI, software developers with extensive iOS development experience using UIkit transitioning to SwiftUI, as well as mobile consultants and engineers who want to gain an in-depth understanding of the framework. Newcomers equipped with knowledge of Swift, UIkit, XCode, and asynchronous programming will find this book invaluable for launching a career in mobile software development with iOS.

Format PDF
Size 13.1 MB
9
Views
0
Downloads
0.00
Total Donations
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
An iOS Developer’s Guide to SwiftUI Design and build beautiful apps quickly and easily with minimum code Michele Fadda
Page 3
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 Square Birmingham B3 1RB, UK ISBN 978-1-80181-362-4 www.packtpub.com
Page 4
Dedicated to my love, Stefania. – Michele Giuseppe Fadda
Page 5
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.
Page 6
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.
Page 7
(This page has no text content)
Page 8
Preface xv Part 1: Simple Views 1 Exploring the Environment – Xcode, Playgrounds, and SwiftUI 3 Technical requirements 4 Exploring SwiftUI with Xcode 4 A brief tour of Xcode 4 Your first SwiftUI project 18 Creating a SwiftUI project 18 Creating a multi-platform project 22 Previews and the simulator 25 Playgrounds 29 The app submission process 32 Certificates 32 Mobile provisioning profiles 33 The application submission process 34 Summary 36 2 Adding Basic UI Elements and Designing Layouts 37 Technical requirements 37 Reusing views code 37 More about Text 43 Managing space in SwiftUI 45 The padding modifier 45 The .frame modifier 46 The .alignment modifier 47 The Spacer 51 The Divider 54 Digging deeper into stacks 55 Overview of stacks 55 HStack 58 ZStack 58 Summary 64 Table of Contents
Page 9
Table of Contentsviii 3 Adding Interactivity to a SwiftUI View 65 Technical requirements 66 Passing values at view creation 66 Responding to a button tap 67 Property wrappers 70 Limitations of @State 71 Changing a view appearance dynamically using modifiers 73 Bidirectional binding with Picker 76 Final notes on Subviews and @Binding, Classes, and @ObservableObject 78 Summary 83 Part 2: Scrollable Views 4 Iterating Views, Scroll Views, FocusState, Lists, and Scroll View Reader 87 Technical requirements 87 Iterating views 87 Hiding or showing the keyboard in a form using @FocusState 94 Scroll views 96 Controlling scrolling programmatically using ScrollViewReader 100 Summary 104 5 The Art of Displaying Grids 105 Technical requirements 105 Displaying grids in iOS 106 The Grid view 106 Creating a simple static grid 111 Lazy grids 116 Using GridItem to control the layout of LazyVGrid 119 Scrolling horizontally and sizing the grid automatically 120 Conditional formatting of a view 121 Reacting to device rotation 124 Summary 126
Page 10
Table of Contents ix Part 3: SwiftUI Navigation 6 Tab Bars and Modal View Presentation 129 Technical requirements 129 Creating a standard tab bar 129 Creating custom tab bars 136 Adapting your code to different versions of the operating system 144 The hitchhiker’s guide to modal navigation 145 Showing a modal sheet 145 Showing alerts 150 The popover 152 Presentation detents 156 Summary 158 7 All About Navigation 159 Technical requirements 159 Navigation as a concept in iOS and other platforms 159 Showing a tab bar title with NavigationView 161 Presenting views with NavigationLink (pre-iOS 16) 163 Adding buttons to NavigationView and activating navigation programmatically 166 Using navigationDestination with NavigationStack 172 Using NavigationPath to control the navigation stack 174 NavigationSplitView – multicolumn navigation 177 Direct navigation stack manipulation with NavigationPath 181 Saving and loading the navigation stack 184 Summary 187
Page 11
Table of Contentsx Part 4: Graphics and Animation 8 Creating Custom Graphics 191 Technical requirements 191 Creating custom modifiers 191 Drawing with the Canvas 195 Using CALayers in SwiftUI 201 Custom layout 204 Summary 207 9 An Introduction to Animations in SwiftUI 209 Technical requirements 210 Gestures 210 Basic gestures 210 Creating implicit animations 213 Explicit SwiftUI animations 216 Transitions 222 The .transition() modifier 223 The matchedGeometryEffect modifier 226 Summary 229 Part 5: App Architecture 10 App Architecture and SwiftUI Part I: Practical Tools 233 Diagrams 234 Dependency inversion 235 Clean Architecture 241 Different ways to decouple 244 Initializer injection 245 Method injection 246 Property injection 247 A matter of state 248 iOS 17 changes in state management 251 Other ways to chop your code 252 Summary 254
Page 12
Table of Contents xi 11 App Architecture and SwiftUI Part II – the Theory 255 Keeping it light enough 256 Conflict and the role of the architect 260 What good software architecture is and what it is not 264 Don’t be shy; ask an expert! 267 The origin of software patterns 271 Agency theory and bad architecture 273 Clean Architecture 274 TCA, The Composable Architecture 278 Summary 281 Part 6: Beyond Basics 12 Persistence with Core Data 285 What is persistency? 285 What is Core Data? 289 Understanding Core Data framework classes 291 Using Core Data with SwiftUI 293 Creating a Core Data project 294 Working with the data model file 302 Core Data migrations 306 The SQLite data file 308 CloudKit 311 Summary 312 13 Modern Structured Concurrency 313 A brief introduction to concurrency 314 Understanding traditional concurrency mechanisms 315 Threads 315 Callbacks and event loops 316 GCD 316 What is structured concurrency? 317 Using the async/await syntax 318 Understanding tasks 325 Task groups 327 Asynchronous streams 335 Actors 340 MainActor 342 Bridging old GCD and structured concurrency 345 Summary 346
Page 13
Table of Contentsxii 14 An Introduction to SwiftData 347 Technical requirements 348 Understanding the differences between SwiftData and Core Data 348 SwiftData and SwiftUI 349 Exploring changes in the binding mechanisms 350 Creating a data model 354 Understanding relationships in SwiftData 360 One-to-one relationships 360 One-to-many relationships 361 Many-to-one relationships 361 Many-to-many relationships 362 Cascading deletion rules 363 Fetching data 363 Filtering data with predicates 363 Summary 364 15 Consuming REST Services in SwiftUI 365 Technical requirements 366 An overview of REST 366 Ports 373 Understanding REST requests in Swift 373 Codable, Encodable, and Decodable protocols 375 Using URLSession 380 Implementing HTTP methods 381 Setting headers 381 Handling errors 382 URLProtocol 388 Summary 392 16 Exploring the Apple Vision Pro 393 Technical requirements 393 Tools for visionOS development 394 An overview of Unity and RealityKit 395 First steps with visionOS development 398 Summary 410
Page 14
Table of Contents xiii Index 411 Other Books You May Enjoy 420
Page 15
(This page has no text content)
Page 16
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.
Page 17
Prefacexvi 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.
Page 18
Preface xvii 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.
Page 19
Prefacexviii 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 .
Page 20
Preface xix 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 customercare@ packtpub.com 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 copyright@packt.com 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.
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
Back to List