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 to solving the most common problems and learning best practices while building SwiftUI apps

Arrow left icon
Product type Paperback
Published in Nov 2021
Publisher Packt
ISBN-13 9781803234458
Length 616 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Giordano Scalzo Giordano Scalzo
Author Profile Icon Giordano Scalzo
Giordano Scalzo
Edgar Nzokwe Edgar Nzokwe
Author Profile Icon Edgar Nzokwe
Edgar Nzokwe
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. Chapter 1: Using the Basic SwiftUI Views and Controls 2. Chapter 2: Going Beyond the Single Component with Lists and Scroll Views FREE CHAPTER 3. Chapter 3: Exploring Advanced Components 4. Chapter 4: Viewing while Building with SwiftUI Preview 5. Chapter 5: Creating New Components and Grouping Views with Container Views 6. Chapter 6: Presenting Extra Information to the User 7. Chapter 7: Drawing with SwiftUI 8. Chapter 8: Animating with SwiftUI 9. Chapter 9: Driving SwiftUI with Data 10. Chapter 10: Driving SwiftUI with Combine 11. Chapter 11: SwiftUI Concurrency with async await 12. Chapter 12: Handling Authentication and Firebase with SwiftUI 13. Chapter 13: Handling Core Data in SwiftUI 14. Chapter 14: Creating Cross-Platform Apps with SwiftUI 15. Chapter 15: SwiftUI Tips and Tricks 16. Other Books You May Enjoy

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
        init(_ someTitle:String){
            title = someTitle
        }
    }
  2. In our ContentView struct, let's add a collection of TodoItem instances:
        @State var todos = [
            TodoItem("Eat"),
            TodoItem("Sleep"),
            TodoItem("Code")
        ]
  3. Replace the Text view in the body with a List and a TextField view that displays the collection of todo items:
        var body: some View {
            List($todos) { $todo in
                TextField("Number", text: $todo.title)
          }
        }

    Run the preview in canvas. You should be able to edit the text in each row, as shown in the following screenshot:

Figure 2.10 – Editable Collections preview

Figure 2.10 – Editable Collections preview

Click on any of the other rows and edit it to your heart's content.

How it works…

Let's start by looking at how editable lists were handled before SwiftUI 3. Before SwiftUI 3, the code for an editable list of items would use list indices to create bindings to a collection, as follows:

List(0..<todos.count) { index in
  TextField("Todo", text: $todos[index].title)
}

Not only was such code slow, but editing a single item caused SwiftUI to re-render the entire List of elements, leading to flickering and slow UI updates.

With SwiftUI 3, we can pass a binding to a collection of elements, and SwiftUI will internally handle binding to the current element specified in the closure. Since the whole of our collection conforms to the Identifiable protocol, each of our list items can be uniquely identified by its id parameter; therefore, adding or removing items from the list does not change list item indices and does not cause the entire list to be re-rendered.

You have been reading a chapter from
SwiftUI Cookbook - Second Edition
Published in: Nov 2021
Publisher: Packt
ISBN-13: 9781803234458
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 $19.99/month. Cancel anytime