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
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
SwiftUI Cookbook
SwiftUI Cookbook

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

eBook
€17.99 €26.99
Paperback
€33.99
Subscription
Free Trial
Renews at €18.99p/m

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

Using the Basic SwiftUI Views and Controls

SwiftUI was launched during Apple’s Worldwide Developer Conference (WWDC) in June 2019. Since then, its popularity has kept increasing as it has been adopted widely by the Apple developer community. Apple also releases updates every year, adding new and exciting capabilities to SwiftUI.

SwiftUI is a UI framework that ditches UIKit concepts such as Auto Layout for an easier-to-use declarative programming model. SwiftUI is Apple’s preferred way to build user interfaces. It is a platform-agnostic framework that allows the fast and easy creation of applications that work across Apple platforms (iOS, iPadOS, macOS, WatchOS, and tvOS).

There is no question today about the need to learn about SwiftUI. Apple released the fifth iteration of the framework in 2023 and it is adding more features every year. Here are some other compelling reasons to be proficient in SwiftUI:

  • SwiftUI apps can work alongside UIKit apps: You can slowly convert your app’s user interface (UI) to SwiftUI, one screen at a time.
  • Industry adoption: SwiftUI has already been adopted by the industry as it was released four years ago. Just looking at job postings for iOS developers, you’ll find out that most of them require experience with SwiftUI. Learning about SwiftUI is a must for current iOS development jobs. In a few more years, SwiftUI will dominate the app development for all the Apple platforms, the same way that Swift took over from Objective-C a few years ago.
  • Low learning curve: SwiftUI offers a low learning curve for people who have used declarative programming before. It is also a great way to start learning declarative programming for those with little to no experience.
  • Live previews increase speed: SwiftUI live previews provide an instant preview of your UI without having to recompile the whole app. You can quickly prototype apps and make any changes required by your users. This greatly improves the speed of UI development.

This book is designed to be your SwiftUI reference material. Each project focuses on a single concept so that you can understand each concept thoroughly, and then combine multiple concepts to build amazing applications.

In this chapter, we will learn about views and controls, SwiftUI’s visual building blocks for app user interfaces. The following recipes will be covered:

  • Laying out components
  • Dealing with text
  • Using images
  • Adding buttons and navigating with them
  • Beyond buttons: using advanced pickers
  • Applying groups of styles using ViewModifier
  • Separating presentation from content with ViewBuilder
  • Simple graphics using San Francisco Symbols (SF symbol)
  • Integrating UIKit into SwiftUI—the best of both worlds
  • Adding SwiftUI to a legacy UIKit app
  • Exploring more views and controls

Technical requirements

The code in this chapter is based on Xcode 15.0 and iOS 17.0. You can download and install the latest version of Xcode from the App Store. You’ll also need to be running macOS Ventura (13.4) or newer.

Simply search for Xcode in the App Store and select and download the latest version. Launch Xcode and follow any additional installation instructions that your system may prompt you with. Once Xcode has fully launched, you’re ready to go.

All the code examples for this chapter can be found on GitHub at https://github.com/PacktPublishing/SwiftUI-Cookbook-3rd-Edition/tree/main/Chapter01-Using-the-basic-SwiftUI-Views-and-Controls/.

What’s new in SwiftUI

SwiftUI has been evolving since the day it was announced in 2019. Every year, Apple adds new APIs and SwiftUI becomes more and more powerful. At the time of this writing, it is possible to create an iOS app exclusively using SwiftUI, without having to integrate UIKit. Since the previous edition of this book, Apple added new functionality to SwiftUI.

In WWDC 2022, Apple added new features to SwiftUI, improved some existing features, and even deprecated some of the APIs just introduced a few years ago. These are the most relevant features:

  • Swift Charts, which allows you to create data visualizations across all Apple platforms
  • New data-driven navigation with NavigationStack and NavigationSplitView
  • Enhancements to Form, to support multi-platform apps with a single code base:
    • LabeledContent view to display pairs of data, like key-value pairs or title and description, inside forms
    • Deeper customization of multi-line TextField instances
    • New MultiDatePicker control to select more than one date
    • New mixed-state controls for Toggle and Picker views and a new format for Stepper views.
  • Table, introduced in macOS 12, now available on iPadOS 16 and iOS 16, and new toolbar customization for iPadOS
  • PhotosPicker view, a multi-platform and privacy-preserving API for picking photos and videos
  • ShareLink view, which enables the presentation of the share sheet even in WatchOS
  • Transferable protocol, to share data between apps
  • ShapeStyle extensions like gradient and shadow, which can also be applied to SFSymbols
  • Grid, to arrange content in a two-dimensional way
  • Layout protocol to create full-custom layouts

In WWDC 2023, Apple added more functionality to SwiftUI. These are the most relevant features:

  • Interactivity and animation added to widgets
  • Improvement to Xcode previews with a new Preview(_:traits:body:) macro that supports UIKit and AppKit out of the box
  • Native SwiftUI support for MapKit
  • Interactivity and pie charts added to Swift Charts
  • Navigation, date pickers, and toolbars available in WatchOS 10
  • SwiftData, a successor of CoreData, used to persist data between app launches
  • The Observable macro, and new @State, @Environment, and @Bindable property wrappers, offering a new way of sharing data throughout the app
  • New powerful animations with the new spring animation, the PhaseAnimator struct, and the Keyframe Animator and CustomAnimation protocol
  • Inspector, a new modal presentation with the inspector(isPresented:content:) view modifier
  • Symbol Effects, animated symbols added to SF Symbols 5
  • New powerful scrolling APIs: transition effects, scroll position, paged scrolling, and inset control
  • Enhancements to list and tables: item selection, expanding sections programmatically, column visibility, column header visibility, hierarchical rows, and alternating row background
  • New dialog customizations, new gestures, and new input events

Laying out components

In this very first recipe of the book, we will start laying out components. In SwiftUI, our user interface is composed of different elements. It is very important to understand how to group components together in different layouts. SwiftUI uses three basic layout components, VStack, HStack, and ZStack. Use the VStack view to arrange components on a vertical axis, HStack to arrange components on a horizontal axis, and—you guessed it right—use the ZStack to arrange components along the vertical and horizontal axis.

In this recipe, we will also look at spacing and adjust the position used to position elements. We will also look at how Spacer and Divider can be used for layout.

Getting ready

Let’s start by creating a new SwiftUI project called TheStacks. Use the following steps:

  1. Start Xcode (Finder | Applications | Xcode).
  2. Click on Create a new Xcode project from the left pane.
  3. The following screen asks us to choose an Xcode template. Select iOS, and then App. Click Next.
  4. A screen to select the options for the project will appear. Enter the product name, TheStacks.
  5. Make sure that Interface is set to SwiftUI, Language is set to Swift, and Storage is set to None. Click Next.
  6. Select the folder location to store the project and choose if you want to create a Git repository or not. Then click Create.

How to do it…

Let’s implement the VStack, HStack, and ZStack within a single screen to better understand how each works and the differences between them. The steps are given here:

  1. Select the Contentview/Contentview.swift file on the navigation pane (left side of Xcode).
  2. Replace the content of the body variable with a VStack and some Text views:
        var body: some View {
            VStack {
                Text("VStack Item 1")
                Text("VStack Item 2")
                Text("VStack Item 3")
            }
            .background(.blue)
        }
    
  3. Press Cmd + Option + Enter if the canvas is not visible, then click on the Resume button above the canvas window to display the resulting view:

Figure 1.1: VStack with three items

  1. Add a Spacer and a Divider between VStack Item 2 and VStack Item 3:
    Spacer()
    Divider()
       .background(.black)
    
  2. The content expands and covers the screen’s width and height, as follows:

Figure 1.2: VStack + Spacer + Divider

  1. Add an HStack and a ZStack below VStack Item 3:
    HStack{
       Text("HStack Item 1")
       Divider()
           .background(.black)
       Text("HStack Item 2")
       Divider()
            .background(.black)
       Spacer()
       Text("HStack Item 3")
    }
    .background(Color.red)
    ZStack{
       Text("ZStack Item 1")
           .padding()
           .background(.green)
           .opacity(0.8)
       Text("ZStack Item 2")
           .padding()
           .background(.green)
           .offset(x: 80, y: -400)
    }
    
  2. The preview should look like the following screenshot (it may vary depending on the device selected for previews):

Figure 1.3: VStack, HStack, and ZStack

This concludes our recipe on using stacks. Going forward, we’ll make extensive use of VStack and HStack to position various components in our views.

How it works…

In Xcode 15, a new iOS app project with SwiftUI selected as the interface option starts with a VStack that includes an Image view and a Text view located at the center of the screen. We replaced the content provided by the template with our own VStack, with three embedded Text views. SwiftUI container views like VStack determine how to display content by using the following steps:

  1. Figure out its internal spacing and subtract that from the size proposed by its parent view.
  2. Divide the remaining space into equal parts.
  3. Process the size of its least flexible view.
  4. Divide the remaining unclaimed space by the unallocated space, and then repeat Step 2.
  5. The stack then aligns its content and chooses its own size to exactly enclose its children.

Adding the Spacer() forces the view to use the maximum amount of vertical space. This is because the Spacer() is the most flexible view—it fills the remaining space after all other views have been displayed.

The Divider() component is used to draw a horizontal line across the width of its parent view. That is why adding a Divider() view stretched the VStack background from just around the Text views to the entire width of the VStack. By default, the divider line does not have a color. To set the divider color, we add the .background(.black) modifier. Modifiers are methods that can be applied to a view to return a new view. In other words, it applies changes to a view. Examples include .background(.black), .padding(), and .offset(…).

The HStack container is like the VStack but its contents are displayed horizontally from left to right. Adding a Spacer() in an HStack thus causes it to fill all available horizontal space, and a divider draws a vertical line between components in the HStack.

The ZStack is like HStack and VStack but overlays its content on top of existing items.

There’s more…

You can also use the .frame modifier to adjust the width and height of a component. Try deleting the Spacer() and Divider() from the HStack and then apply the following modifier to the HStack:

.frame(
    maxWidth: .infinity,
    maxHeight: .infinity,
    alignment: .topLeading
)
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
€18.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
€189.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
€264.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 94.97
iOS 17 Programming for Beginners
€33.99
SwiftUI Cookbook
€33.99
Elevate SwiftUI Skills by Building Projects
€26.99
Total 94.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