Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
SwiftUI Cookbook
SwiftUI Cookbook

SwiftUI Cookbook: A guide for building beautiful and interactive SwiftUI apps , Third Edition

Arrow left icon
Profile Icon Juan C. Catalan
Arrow right icon
₱1284.99 ₱1836.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (20 Ratings)
eBook Dec 2023 798 pages 3rd Edition
eBook
₱1284.99 ₱1836.99
Paperback
₱2296.99
Subscription
Free Trial
Arrow left icon
Profile Icon Juan C. Catalan
Arrow right icon
₱1284.99 ₱1836.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (20 Ratings)
eBook Dec 2023 798 pages 3rd Edition
eBook
₱1284.99 ₱1836.99
Paperback
₱2296.99
Subscription
Free Trial
eBook
₱1284.99 ₱1836.99
Paperback
₱2296.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

SwiftUI Cookbook

Adding SwiftUI to a legacy UIKit app

In this recipe, we will learn how to navigate from a UIKit view to a SwiftUI view while passing a secret text to our SwiftUI view. This recipe assumes prior knowledge of UIKit and it is most useful to developers who want to integrate SwiftUI into a legacy UIKit app. If this is not your case, feel free to skip to the next recipe. We'll be making use of a UIKit storyboard, a visual representation of the UI in UIKit. The Main.storyboard file is to UIKit what the ContentView.swift file is to SwiftUI. They are both the default home views that are created when you start a new project.We start off this project with a simple UIKit project that contains a button.

Getting ready

Get the following ready before starting out with this recipe:

  1. Clone or download the code for this book from GitHub: https://github.com/PacktPublishing/SwiftUI-Cookbook-3rd-Edition-/tree/main/Chapter01-Using-the-basic-SwiftUI-Views-and-Controls/10-Adding-SwiftUI-to-UIKit.
  2. Open the...

Exploring more views and controls

In this section, we introduce some views and controls that did not clearly fit in any of the earlier created recipes. We'll look at the ProgressView, ColorPicker, Link, and Menu views.ProgressView is used to show the degree of completion of a task. There are two types of ProgressView: indeterminate progress views show a spinning circle till a task is completed, while determinate progress views show a bar that gets filled up to show the degree of completion of a task. ColorPicker views allow users to select from a wide range of colors, while Menu views present a list of items that users can choose from to perform a specific action.

Getting ready

Let's start by creating a new SwiftUI project called MoreViewsAndControls.

How to do it…

Let's implement some views and controls in the ContentView.swift file. We will group the controls in Section instances in a List view. Section allows us to include an optional header. The steps are...

Using scroll views

You can use SwiftUI scroll views when the content to be displayed cannot fit in its container. Scroll views create scrolling content where users can use gestures to bring new content into the section of the screen where it can be viewed. Scroll views are vertical by default but can be made to scroll horizontally or vertically.

In this recipe, we will learn how to use horizontal and vertical scroll views.

Getting ready

Let’s start by creating a SwiftUI project called WeScroll.

Optional: If you don’t have it yet, download the San Francisco Symbols (SF Symbols) app here: https://developer.apple.com/sf-symbols/.

As we mentioned in Chapter 1, Using the Basic SwiftUI Views and Controls, SF Symbols is a set of over 5,000 symbols provided by Apple at the time of this writing.

How to do it…

Let’s learn how scroll views work by implementing horizontal and vertical scroll views that display SF symbols for alphabet characters...

Creating a list of static items

List views are like scroll views in that they are used to display a collection of items. However, List views are better for dealing with larger datasets because they do not load the entirety of the datasets in memory.

When we refer to a list of static items, we mean that the information that the list displays is predetermined in our code, and it does not change when the app is running. A good example of this use is the iOS settings app, where we have a list of settings that are fixed by the iOS version. Every time we run the settings app, we see the same list, its content, is static.

In contrast, a list of dynamic items has its content determined every time the app runs. As such, the app needs to accommodate any number of items in the list. One well-known example is the iOS mail app, where we have a list of our latest emails. The content of this list changes every time we run the app, making its content dynamic.

In this recipe, we will...

Using custom rows in a list

The number of lines of code required to display items in a List view row could vary from one to several lines of code. Repeating the code several times or in several places increases the chance of an error occurring and potentially becomes very cumbersome to maintain. One change would require updating the code in several different locations or files.

A custom list row can be used to solve this problem. This custom row can be written once and used in several places, thereby improving maintainability and encouraging reuse.

Let’s find out how to create custom list rows.

Getting ready

Let’s start by creating a new SwiftUI app named CustomRows.

How to do it…

We will reorganize the code in our static lists to make it more modular. We’ll create a separate file to hold the WeatherInfo struct, a separate SwiftUI file for the custom view, WeatherRow, and finally, we’ll implement the components in the ContentView...

Adding rows to a list

The most common actions users might want to be able to perform on a list include adding, editing, and deleting items.

In this recipe, we’ll go over the process of implementing those actions on a SwiftUI list.

Getting ready

Create a new SwiftUI project and call it ListRowAdd.

How to do it…

Let’s create a list with a button at the top that can be used to add new rows to the list. The steps are as follows:

  1. Create a state variable in the ContentView struct that holds an array of numbers:
    @State var numbers = [1,2,3,4]
    
  2. Replace the content of the body property of the ContentView struct with a NavigationStack containing a List view:
    NavigationStack {
       List{
           ForEach(self.numbers, id:\.self){
              number in
              Text("\(number)")
           }
       }
    }
    
  3. Add a .navigationTitle and a navigationBarTitleDisplayMode modifier to the list with a title and an...

Deleting rows from a list

So far, we’ve learned how to add new rows to a list. Now, let’s find out how to use a swipe motion to delete items one at a time.

Getting ready

Create a new SwiftUI app called ListRowDelete.

How to do it…

We will create a list of items and use the list view’s onDelete modifier to delete rows. The steps are as follows:

  1. Add a state variable to the ContentView struct called countries and initialize it with an array of country names:
        @State private var countries = ["USA", "Canada", "Mexico", "England", "Spain", "Cameroon", "South Africa", "Japan", "South Korea"]
    
  2. Replace the content of the body variable with a NavigationStack containing a List view that displays our array of countries. Also, include the onDelete modifier at the end of the ForEach structure:
            NavigationStack {
    ...

Creating an editable List view

Adding an edit button to a List view is very similar to adding a delete button, as seen in the previous recipe. An edit button offers the user the option to quickly delete items by clicking a minus sign to the left of each list row.

Getting ready

Create a new SwiftUI project named ListRowEdit.

How to do it…

The steps for adding an edit button to a List view are similar to the steps we used when adding a delete button. The process is as follows:

  1. Replace the ContentView struct with the following content from the DeleteRowFromList app:
    struct ContentView: View {
        @State private var countries = ["USA", "Canada", "Mexico", "England", "Spain", "Cameroon", "South Africa" , "Japan", "South Korea"]
        var body: some View {
            NavigationStack {
                List {
                    ForEach(countries, id: \.self) { country in...

Moving the rows in a List view

In this recipe, we’ll create an app that implements a List view that allows users to move and reorganize rows.

Getting ready

Create a new SwiftUI project named MovingListRows.

How to do it…

To make the List view rows movable, we’ll add a modifier to the List view’s ForEach struct, and then we’ll embed the List view in a navigation view that displays a title and an edit button. The steps are as follows:

  1. Add a @State variable to the ContentView struct that holds an array of countries:
        @State private var countries = ["USA", "Canada", "Mexico", "England", "Spain", "Cameroon", "South Africa" , "Japan", "South Korea"]
    
  2. Replace the body variable’s text view with a NavigationStack, a List, and modifiers for navigating. Also, notice that the .onMove modifier is applied to the ForEach...

Adding sections to a list

In this recipe, we will create an app that implements a static list with sections. The app will display a list of countries grouped by continent.

Getting ready

Let’s start by creating a new SwiftUI app in Xcode named ListWithSections.

How to do it…

We will add a Section view to our List to separate groups of items by section titles. Proceed as follows:

  1. (Optional) Open the ContentView.swift file and replace the body content with a NavigationStack. Wrapping the List in a NavigationStack allows us to add a title and navigation items to the view:
    NavigationStack {
    }
    
  2. Add a list and section to NavigationStack (or body view if you skipped the optional Step 1). Also, add a listStyle and navigationTitle and navigationBarTitleDisplayMode modifiers:
    List {
        Section(header: Text("North America")){
            Text("USA")
            Text("Canada")
            Text("Mexico...

Creating editable collections

Editing lists has always been possible in SwiftUI but before WWDC 2021 and SwiftUI 3, doing so was very inefficient because SwiftUI did not support binding to collections. Let’s use bindings on a collection and discuss how and why it works better now.

Getting ready

Create a new SwiftUI project and name it EditableListsFields.

How to do it…

Let’s create a simple to-do list app with a few editable items. The steps are as follows:

  1. Add a TodoItem struct below the import SwiftUI line:
    struct TodoItem: Identifiable {
        let id = UUID()
        var title: String
    }
    
  2. In our ContentView struct, let’s add a collection of TodoItem instances:
        @State private var todos = [
            TodoItem(title: "Eat"),
            TodoItem(title: "Sleep"),
            TodoItem(title: "Code")
        ]
    
  3. Replace the body content with a List that displays the collection...

Using searchable lists

List views can hold from one to an uncountable number of items. As the number of items in a list increases, it is usually helpful to provide users with the ability to search through the list for a specific item without having to scroll through the whole list.

In this recipe, we’ll introduce the searchable(text:placement:prompt:) modifier, which marks the view as searchable and configures the display of a search field, and discuss how it can be used to search through items in a list.

Getting ready

Create a new SwiftUI project and name it SearchableLists.

How to do it…

Let’s create an app to search through different types of food. The steps are as follows:

  1. Add a new Swift file to the project called Food, which will contain the data used for the project. We use a struct to model different types of food. The struct has two properties, a string with the name of the food, and a category, which is an enum representing...

Using searchable lists with scopes

In this recipe, we will improve our searchable list with the addition of the searchScopes(_:activation:_:) modifier, which allows us to narrow the scope of our searches.

The scope modifier could be useful to further reduce the scope of our search and reduce the time it takes to find an item. In our case, we have a list of food items, belonging to three different categories: meat, fruit, and vegetables. Selecting a specific scope narrows the search and gives the user a quicker way of finding the desired item.

This new modifier was introduced in iOS 16.4 and it is a nice mid-cycle addition, introduced with a minor version update of iOS. Most of the updates to iOS are usually announced in June, during the WWDC conference, and then introduced in September when the new version of iOS is released to users. However, Apple also releases new features during the year as is the case for the one we are using in this recipe.

Getting ready...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Unlock advanced controls and animations with SwiftUI 5, taking your app development skills to the next level
  • Visualize data effortlessly using Swift Charts enhancing your app's data-driven capabilities
  • Develop for multiple platforms, including iOS, macOS, and watchOS, and become a versatile app developer
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

SwiftUI is the modern way to build user interfaces for iOS, macOS, and watchOS. It provides a declarative and intuitive way to create beautiful and interactive user interfaces. The new edition of this comprehensive cookbook includes a fully updated repository for SwiftUI 5, iOS 17, Xcode 15, and Swift 5.9. With this arsenal, it teaches you everything you need to know to build beautiful and interactive user interfaces with SwiftUI 5, from the basics to advanced topics like custom modifiers, animations, and state management. In this new edition, you will dive into the world of creating powerful data visualizations with a new chapter on Swift Charts and how to seamlessly integrate charts into your SwiftUI apps. Further, you will be able to unleash your creativity with advanced controls, including multi-column tables and two-dimensional layouts. You can explore new modifiers for text, images, and shapes that give you more control over the appearance of your views. You will learn how to develop apps for multiple platforms, including iOS, macOS, watchOS, and more. With expert insights, real-world examples, and a recipe-based approach, you’ll be equipped to build remarkable SwiftUI apps that stand out in today’s competitive market.

Who is this book for?

This book is for mobile developers who want to learn SwiftUI as well as experienced iOS developers transitioning from UIKit to SwiftUI. The book assumes knowledge of the Swift programming language. Knowledge of object-oriented design and data structures will be useful but not necessary. You'll also find this book to be a helpful resource if you're looking for reference material regarding the implementation of various features in SwiftUI.

What you will learn

  • Create stunning, user-friendly apps for iOS 17, macOS 14, and watchOS 10 with SwiftUI 5
  • Use the advanced preview capabilities of Xcode 15
  • Use async/await to write concurrent and responsive code
  • Create powerful data visualizations with Swift Charts
  • Enhance user engagement with modern animations and transitions
  • Implement user authentication using Firebase and Sign in with Apple
  • Learn about advanced topics like custom modifiers, animations, and state management
  • Build multi-platform apps with SwiftUI

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 26, 2023
Length: 798 pages
Edition : 3rd
Language : English
ISBN-13 : 9781805129844
Vendor :
Apple
Languages :
Concepts :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 26, 2023
Length: 798 pages
Edition : 3rd
Language : English
ISBN-13 : 9781805129844
Vendor :
Apple
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 6,379.97
Elevate SwiftUI Skills by Building Projects
₱1785.99
SwiftUI Cookbook
₱2296.99
iOS 17 Programming for Beginners
₱2296.99
Total 6,379.97 Stars icon

Table of Contents

19 Chapters
Using the Basic SwiftUI Views and Controls Chevron down icon Chevron up icon
Displaying Scrollable Content with Lists and Scroll Views Chevron down icon Chevron up icon
Exploring Advanced Components Chevron down icon Chevron up icon
Viewing while Building with SwiftUI Preview in Xcode 15 Chevron down icon Chevron up icon
Creating New Components and Grouping Views with Container Views Chevron down icon Chevron up icon
Presenting Views Modally Chevron down icon Chevron up icon
Navigation Containers Chevron down icon Chevron up icon
Drawing with SwiftUI Chevron down icon Chevron up icon
Animating with SwiftUI Chevron down icon Chevron up icon
Driving SwiftUI with Data Chevron down icon Chevron up icon
Driving SwiftUI with Combine Chevron down icon Chevron up icon
SwiftUI Concurrency with async await Chevron down icon Chevron up icon
Handling Authentication and Firebase with SwiftUI Chevron down icon Chevron up icon
Persistence in SwiftUI with Core Data and SwiftData Chevron down icon Chevron up icon
Data Visualization with Swift Charts Chevron down icon Chevron up icon
Creating Multiplatform Apps with SwiftUI Chevron down icon Chevron up icon
SwiftUI Tips and Tricks Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(20 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Vinicius Carvalho Marques Feb 23, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Livro muito bom e completo com muitos elementos para aprender sobre SwiftUI e todos os seus componentes.
Feefo Verified review Feefo
Bhaskar Apr 08, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Every topic explained clearly and beginners can understand.
Amazon Verified review Amazon
Nicholas Mar 07, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a great read for developers already acquainted with Swift on some minor level and looking for efficient ways to design and implement common UI elements. While it dedicates a chapter to lay down the basics—which can serve as a refresher or a crash course for those somewhat new to the framework—the book mainly excels in offering concise, practical solutions aimed at specific problems as opposed to an opus on the entire language (This is the purpose of a cookbook btw).The update to include XCode 15 is particularly noteworthy, addressing the shifts and nuances introduced in the IDE since the book's previous editions. This helps us stay current with not just the language but also the tools we use to develop with it.A standout addition to this edition is the revised chapter on CoreData, incorporating SwiftData. Given the newness of SwiftData, the book offers a chance to explore its use in these example scenarios. This update really shows the author's commitment to keeping us up to date with the latest developments in Swift programming.Furthermore, the new chapter on data visualization caters to developers involved in data analysis, offering advanced techniques and insights into visual data representation with Swift Charts. This was the most interesting addition that set it aside from the previous versions of the book.Overall, I def recommend this for Swift developers seeking to enhance their UI design skills with the latest tools and techniques, supported by practical examples. Just keep in mind its strongest as a reference tool, not really a 'teach me everything' tool.
Amazon Verified review Amazon
Amazon Customer Jan 02, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As a programmer who is new to SwiftUI, but has years of programming experience, this book hits the perfect level of theory and practice which allows the reader to quickly absorb the relevant concepts of this new UI paradigm. The recipes in this well explained introduction to the various SwiftUI building blocks will get you up and going, and then enable you to achieve useful working examples of elements of iOS applications.The author provides useful step-by-step instructions and illustrated outputs to reinforce the concepts presented. An excellent way to teach yourself this important technology.
Amazon Verified review Amazon
Joaquin L. Navarro Jan 06, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you are a software developer for Apple platforms: iOS, macOS and watchOS, interested in learning a modern approach to build user interfaces using Swift UI, this book is for you. SwiftUI has become Apple’s recommended way of building User Interfaces since its introduction in 2019 until the present day (2024).If you prefer a practical approach to learning programming concepts, this book contains hundreds of easy to follow, and implement, examples. This library of examples, by itself, makes the book a valuable resource for Apple developers, juniors and seniors alike, to use as a reference, or starting point, when building appealing user interfaces.The book covers a range of topics: from introductory ones, like basic SwiftUI controls, Lists and Scroll Views; to more advanced topics like Swift UI Concurrency and async await, building hierarchical content and creating widgets.Portions of relevant code are included in the book, together with “How it works…” sections that provide more clarity. There are also many “Important Notes” in which the author provides very valuable nuggets of advice.So, get your Mac ready (with macOS Ventura 13.5 and XCode 15) and embark on this journey of learning to create eye appealing mobile apps using SwiftUI.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.