The pull-to-refresh gesture has been around since the early days of the iPhone when Tweetie launched in around 2008. It provided a way for a table view to refresh by swiping down to a point where the refresh was triggered.
Apple introduced it in the UIRefreshControl class in iOS 6. In iOS 15 in 2021, Apple added support natively to SwiftUI.
It is now known as refreshable and is an instance method in the View. Lets take a look at how it works.
struct ContentView: View {
@State private var items: [String] = ["Item 1", "Item 2", "Item 3"]
var body: some View {
NavigationView {
List(items, id: \.self) { item in
Text(item)
}
.refreshable {
await refreshData()
}
.navigationTitle("Pull to Refresh")
}
}
func refreshData() async {
// Delay added to simulate a call to an API
try? await Task.sleep(nanoseconds: 2_000_000_000)
items.append("New Item \(items.count + 1)")
}
}
The sample code above shows how you can implement .refreshable. We start with an array of strings that uses the @State property wrapper. This property wrapper makes it so that any changes to the items variable automatically refreshes the view. We initialise it with three strings, Item’s 1 to 3.
Our view contains a NavigationView with a title, “Pull to Refresh”, and within it, a List view that iterates over the items.
On lines 9 – 11 we make use of the .refreshable method, and within there, make a call to the refreshData method. This method uses async/await so that it can run and do its thing without holding up the UI.
On line 18 we introduce a delay. Rather than make an actual call to an API here to get the data, I just simulate a couple of second passing to give the effect of it doing something.
When the time passes, line 19 appends a new string to the array, and when this happens, the @State property wrapped items automatically refreshes the view to add the item.
This tutorial is quite simple, but if you have a view that could benefit from being forced to refresh or do something else useful, then its easy enough to implement with the refreshable method.
Leave a Reply
You must be logged in to post a comment.