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
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

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.swift file. The steps are as follows:

  1. Create a new Swift file called WeatherInfo by going to File | New | File | Swift File (or by using the Command () + N keys).
  2. Create a WeatherInfo struct within the newly created file:
    struct WeatherInfo: Identifiable {
        var id = UUID()
        var image: String
        var temp: Int
        var city: String
    }
  3. Also, add a weatherData variable that holds an array of WeatherInfo:
    let weatherData: [WeatherInfo] = [
         WeatherInfo(image: "snow", temp: 5, city:"New
           York"),
         WeatherInfo(image: "cloud", temp:5, city:"Kansas
           City"),
         WeatherInfo(image: "sun.max", temp: 80, city:"San
           Francisco"),
         WeatherInfo(image: "snow", temp: 5,
           city:"Chicago"),
         WeatherInfo(image: "cloud.rain", temp: 49,
           city:"Washington DC"),
         WeatherInfo(image: "cloud.heavyrain", temp: 60,
           city:"Seattle"),
         WeatherInfo(image: "sun.min", temp: 75,
           city:"Baltimore"),
         WeatherInfo(image: "sun.dust", temp: 65,
           city:"Austin"),
         WeatherInfo(image: "sunset", temp: 78,
           city:"Houston"),
         WeatherInfo(image: "moon", temp: 80,
           city:"Boston"),
         WeatherInfo(image: "moon.circle", temp: 45,
           city:"denver"),
         WeatherInfo(image: "cloud.snow", temp: 8,
           city:"Philadelphia"),
         WeatherInfo(image: "cloud.hail", temp: 5,
           city:"Memphis"),
         WeatherInfo(image: "cloud.sleet", temp:5,
           city:"Nashville"),
         WeatherInfo(image: "sun.max", temp: 80, city:"San
           Francisco"),
         WeatherInfo(image: "cloud.sun", temp: 5,
           city:"Atlanta"),
         WeatherInfo(image: "wind", temp: 88, city:"Las
            Vegas"),
         WeatherInfo(image: "cloud.rain", temp: 60,
            city:"Phoenix"),
         ]
  4. Create a new SwiftUI file by selecting File | New | File | SwiftUI View from the Xcode menu or by using the Command () + N key combination. Name the file WeatherRow.
  5. Add the following weather row design to our new SwiftUI view:
    struct WeatherRow: View {
        var weather: WeatherInfo
        var body: some View {
            HStack {
                Image(systemName: weather.image)
                    .frame(width: 50, alignment: .leading)
                Text("\(weather.temp)°F")
                    .frame(width: 80, alignment: .leading)
                Text(weather.city)
            }
            .font(.system(size: 25))
            .padding()
        }
    }
  6. To preview or update the row design, add a sample WeatherInfo instance to the WeatherRow_Previews function:
    struct WeatherRow_Previews: PreviewProvider {
        static var previews: some View {
            WeatherRow(weather: WeatherInfo(image: "snow",
            temp: 5, city:"New York"))
        }
    }

    The resulting WeatherRow.swift canvas preview should look as follows:

    Figure 2.3 – WeatherRow row preview

    Figure 2.3 – WeatherRow row preview

  7. Open the ContentView.swift file and create a list to display data using the WeatherRow component:
    struct ContentView: View {
        var body: some View {
            List{
                ForEach(weatherData){weather in
                    WeatherRow(weather: weather)
                }
            }
        }
    }

    The resulting canvas preview should look as follows:

Figure 2.4 – CustomRow App preview

Figure 2.4 – CustomRow App preview

Run the app on a device or run a live preview to scroll through and test the app's functionality.

How it works…

WeatherInfo.swift is the model file containing a blueprint of what we want each instance of our weatherInfo struct to contain. We also instantiated an array of the WeatherInfo struct, weatherData, that can be used in other parts of the project previewing and testing areas as we build.

The WeatherRow SwiftUI file is our focus for this recipe. By using this file, we can extract the design of a list row into a separate file and reuse the design in other sections of our project. We added a weather property to our WeatherRow that will hold the WeatherInfo arguments that are passed to our WeatherRow view.

As in the previous recipe, we want the content of each row to be displayed horizontally next to each other, so we enclosed the components related to our weather variable in an HStack.

Important Note

The weatherData array is only necessary during development and should be removed before deployment if such data is obtained at runtime through API calls.

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
Banner background image