Pull To Refresh in SwiftUI

Gabriel Theodoropoulos
6 min readJul 1, 2021
Photo by cottonbro from Pexels

SwiftUI gets better and better every year, and in WWDC 2021 we heard about some great new additions and improvements. One such addition that this post is focusing on is the pull to refresh control; a missing UI element familiar from the UITableView in UIKit, but not available in the first two versions of SwiftUI.

Putting the pull to refresh functionality in action is pretty easy in SwiftUI. We only have to apply a specific view modifier on a List view, and keep one or two things in mind, but crucial to the app’s proper behavior. Let’s go through them.

Using pull to refresh

Consider the following simple example, where we have a list with country names and their flags:

For the sake of the demonstration here, the data is retrieved from a local, custom JSON file that contains a few European countries with URLs to their flag images. Even though there are just a few countries listed initially, the purpose is to add a new country to the top every time we pull to refresh the list.

In order to achieve that, we firstly need a source of truth for the data that we’ll present in the list:

@ObservedObject var countriesModel = CountriesModel()

CountriesModel is an ObservableObject type that implements all the necessary logic that makes the specific example work. There is also an auxiliary type, called CountryData that keeps the actual data for a single country; its name, the URL to the flag image, as well as a unique identifier, because it conforms to the Identifiable protocol.

Note: You can download the demo project of this post to find out all implementation details.

The following snippet creates the actual list:

List(countriesModel.countries, id: \.id) { country in
CountryView(country: country)
}

CountryView is a SwiftUI view that contains an AsyncImage view and a Text view that display the data in each row.

In order to enable the pull to refresh functionality, we’ll apply a brand new view modifier to the List; it’s called…

Gabriel Theodoropoulos

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev

Recommended from Medium

Lists

See more recommendations