
How many apps do you know that implement the pull-to-refresh feature? If you’re interested in learning how to create this helpful functionality in your app, you can read this post.
Let’s start with the basics:
struct ContentView: View {
var body: some View {
NavigationStack {
List(1..<30) { n in
Text("Beer \(n)")
}
.refreshable {
print("Load other beer")
}
}
}
}
This code displays a simple list of beers identified by name, with the important part being the refreshable feature. It’s this last feature that creates the graphical effect for the pull action and executes the code within the parentheses asynchronously (where the print instruction is located).
Real Example
Starting from this point, let’s try to create something a bit more complex and realistic. We aim to load beers, 30 per page, and when we perform the pull action, we want to download and display another 30 beers. The beers are sourced from: https://api.punkapi.com/v2/beers
First, create the struct for the beer, as we only want to retrieve the name:
struct Beer: Codable, Identifiable {
var id: Int
var name: String
}