Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
SwiftUI Cookbook

You're reading from   SwiftUI Cookbook A guide for building beautiful and interactive SwiftUI apps

Arrow left icon
Product type Paperback
Published in Dec 2023
Publisher Packt
ISBN-13 9781805121732
Length 798 pages
Edition 3rd Edition
Languages
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Juan C. Catalan Juan C. Catalan
Author Profile Icon Juan C. Catalan
Juan C. Catalan
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Using the Basic SwiftUI Views and Controls FREE CHAPTER 2. Displaying Scrollable Content with Lists and Scroll Views 3. Exploring Advanced Components 4. Viewing while Building with SwiftUI Preview in Xcode 15 5. Creating New Components and Grouping Views with Container Views 6. Presenting Views Modally 7. Navigation Containers 8. Drawing with SwiftUI 9. Animating with SwiftUI 10. Driving SwiftUI with Data 11. Driving SwiftUI with Combine 12. SwiftUI Concurrency with async await 13. Handling Authentication and Firebase with SwiftUI 14. Persistence in SwiftUI with Core Data and SwiftData 15. Data Visualization with Swift Charts 16. Creating Multiplatform Apps with SwiftUI 17. SwiftUI Tips and Tricks 18. Other Books You May Enjoy
19. Index

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 given here:

  1. Just below the ContentView struct declaration, add the state variables that we’ll be using for various components:
        @State private var progress = 0.5
        @State private var color  = Color.red
        @State private var secondColor  = Color.yellow
        @State private var someText = "Initial value" 
    
  2. Replace the body contents with a List view with a Section view, two ProgressView views, and a Button view:
            List {
                Section(header: Text("ProgressViews")) {
                    ProgressView("Indeterminate progress view")
                    ProgressView("Downloading",value: progress, total:2)
                    Button("More") {
                        if (progress < 2) {
                            progress += 0.5
                        }
                    }
                } 
    }
    
  3. Let’s add another section that implements two labels:
                Section(header: Text("Labels")) {
                    Label("Slow ", systemImage: "tortoise.fill")
                    Label {
                        Text ("Fast")
                            .font(.title)
                    } icon: {
                        Circle()
                            .fill(Color.orange)
                            .frame(width: 40, height: 20, alignment: .center)
                            .overlay(Text("F"))
                    }
                }
    
  4. Now, add a new section that implements a ColorPicker:
                Section(header: Text("ColorPicker")) {
                    ColorPicker(selection: $color ) {
                        Text("Pick my background")
                            .background(color)
                            .padding()
                    }
                    ColorPicker("Picker", selection: $secondColor )
                }
    
  5. Next, add a Link:
                Section(header: Text("Link")) {
                    Link("Packt Publishing", destination: URL(string: "https://www.packtpub.com/")!)
                }
    
  6. Next, add a TextEditor:
                Section(header: Text("TextEditor")) {
                    TextEditor(text: $someText)
                    Text("current editor text:\n\(someText)")
                }
    
  7. Then, add a Menu:
                
                Section(header: Text("Menu")) {
                    Menu("Actions") {
                        Button("Set TextEditor text to 'magic'"){
                            someText = "magic"
                        }
                        Button("Turn first picker green") {
                            color = Color.green
                        }
                        Menu("Actions") {
                            Button("Set TextEditor text to 'real magic'"){
                                someText = "real magic"
                            }
                            Button("Turn first picker gray") {
                                color = Color.gray
                            }
                            
                        }
                    }
                }
    
  8. Finally, let’s improve the style of all the content by applying a listStyle modifier on the List:
    List {
    ...
    }
    .listStyle(.grouped)
    
  9. The resulting view app preview should look like this:

Figure 1.23: More Views and Controls app preview

How it works…

We’ve implemented multiple views in this recipe. Let’s look at each one and discuss how they work.

Indeterminate ProgressView requires no parameters:

ProgressView("Indeterminate progress view")
ProgressView()

Determinate ProgressView components, on the other hand, require a value parameter that takes a state variable and displays the level of completion:

ProgressView("Downloading",value: progress, total:2)

The total parameter in the ProgressView component is optional and defaults to 1.0 if not specified.

Label views were mentioned earlier in the Simple graphics using SF Symbols recipe. Here, we introduce a second option for implementing labels where we customize the design of the label text and icon:

Label {
                    Text ("Fast")
                        .font(.title)
                } icon: {
                    Circle()
                        .fill(Color.orange)
                        .frame(width: 40, height: 20, alignment: .center)
                        .overlay(Text("F"))
                }

Let’s move on to the ColorPicker view. Color pickers let you display a palette for users to pick colors from. We create a two-way binding using the color state variable so that we can store the color selected by the user:

                ColorPicker(selection: $color ) {
                    Text("Pick my background")
                        .background(color)
                        .padding()
                }

Link views are used to display clickable links:

                Link("Packt Publishing", destination: URL(string: "https://www.packtpub.com/")!) 

Finally, the Menu view provides a convenient way of presenting a user with a list of actions to choose from and can also be nested, as seen here:

                Menu("Actions") {
                    Button("Set TextEditor text to 'magic'"){
                        someText = "magic"
                    }
                    Button("Turn first picker green") {
                        color = Color.green
                    }
                    Menu("Actions") {
                        Button("Set TextEditor text to 'real magic'"){
                            someText = "real magic"
                        }
                        Button("Turn first picker gray") {
                            color = Color.gray
                        } 
                    }
                } 

You can add one or more buttons to a menu, each performing a specific action. Although menus can be nested, this should be done sparingly as too much nesting may decrease usability.

After learning the basics of SwiftUI, we concluded the chapter with this recipe, where we used several SwiftUI view components that we could incorporate into our apps.

Learn more on Discord

To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow the QR code below:

https://packt.link/swiftUI

You have been reading a chapter from
SwiftUI Cookbook - Third Edition
Published in: Dec 2023
Publisher: Packt
ISBN-13: 9781805121732
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime