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
Free Learning
Arrow right icon
SwiftUI Cookbook
SwiftUI Cookbook

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

eBook
₹799 ₹2680.99
Paperback
₹3351.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with a Packt Subscription?

Free for first 7 days. ₹800 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781805121732
Vendor :
Apple
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. ₹800 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 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
₹4500 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 ₹400 each
Feature tick icon Exclusive print discounts
₹5000 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 ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 9,310.97
Elevate SwiftUI Skills by Building Projects
₹2606.99
SwiftUI Cookbook
₹3351.99
iOS 17 Programming for Beginners
₹3351.99
Total 9,310.97 Stars icon
Banner background image

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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.