Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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 Discover solutions and best practices to tackle the most common problems while building SwiftUI apps

Arrow left icon
Product type Paperback
Published in Oct 2020
Publisher Packt
ISBN-13 9781838981860
Length 614 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Edgar Nzokwe Edgar Nzokwe
Author Profile Icon Edgar Nzokwe
Edgar Nzokwe
Giordano Scalzo Giordano Scalzo
Author Profile Icon Giordano Scalzo
Giordano Scalzo
Arrow right icon
View More author details
Toc

Table of Contents (15) 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: Viewing while Building with SwiftUI Preview 4. Chapter 4: Creating New Components and Grouping Views in Container Views 5. Chapter 5: Presenting Extra Information to the User 6. Chapter 6: Drawing with SwiftUI 7. Chapter 7: Animating with SwiftUI 8. Chapter 8: Driving SwiftUI with Data 9. Chapter 9: Driving SwiftUI with Combine 10. Chapter 10: Handling Authentication and Firebase with SwiftUI 11. Chapter 11: Handling Core Data in SwiftUI 12. Chapter 12: Cross-Platform SwiftUI 13. Chapter 13: SwiftUI Tips and Tricks 14. 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. A custom list row is used when working with several lines of code within a list view row. Implementing custom lists improves modularity and readability, and allows code reuse.

Getting ready

Let's start by creating a new SwiftUI app called CustomRows.

How to do it…

We will reuse part of the code in the static list and clean it up to make it more modular. We create a separate file to hold the WeatherInfo struct, a separate SwiftUI file for the custom WeatherRow, and finally, we implement the components in the ContentView.swift file. The steps are as follows:

  1. Create a new Swift file called WeatherInfo by selecting File | New | File | Swift File or by pressing the ⌘ + N keys.
  2. Define the WeatherInfo struct within the WeatherInfo.swift file:
    struct WeatherInfo: Identifiable {
        var id = UUID()
        var image: String
        var temp: Int
        var city: String
    }
  3. Create 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 or by pressing the + N keys.
  5. Name the file WeatherRow.
  6. Add the following code to design the look and functionality of the weather row:
    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()
        }
    }
  7. Add the following code to the WeatherRow_Previews struct to display information from a sample WeatherInfo struct instance:
    static var previews: some View {
            WeatherRow(weather: WeatherInfo(image: "snow",           temp: 5, city:"New York"))
        }
  8. The resulting WeatherRow.swift canvas preview should look as follows:
    Figure 2.3 – WeatherRow preview

    Figure 2.3 – WeatherRow preview

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

    The resulting canvas preview should look as follows:

Figure 2.4 – CustomRowApp preview

Figure 2.4 – CustomRowApp preview

Run the app live preview and admire the work of your own hands.

How it works…

The WeatherInfo Swift file contains the description of the WeatherInfo struct. Our dataset, an array of WeatherInfo variables, was also declared in the file to make it available to other sections of the project.

The WeatherRow SwiftUI file contains the design we will use for each weather row. The weather property within WeatherRow will hold the WeatherInfo arguments passed to the view. HStack in the body of WeatherRow is used to display data from weather variables since a SwiftUI view can only return one view at a time. When displaying multiple views – an image view and two text views, in this case – the views are all encased in an HStack component. The .frame(width: 50, alignment: .leading) modifier added to the image and first text view sets the width used by the element it modifies to 50 units and the alignment to the .leading parameter.

Finally, the .font(.system(size: 25)) and .padding() modifiers are added to HStack to increase the text and image font sizes and add padding to all sides of WeatherRow.

You have been reading a chapter from
SwiftUI Cookbook
Published in: Oct 2020
Publisher: Packt
ISBN-13: 9781838981860
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