Mastering Refreshable in SwiftUI : Pull to refresh
The refreshable
modifier in SwiftUI provides a way to allow users to manually refresh the content of a view. When added to a view, it adds a pull-to-refresh function to initiate a refresh action.
func refreshable(action: @escaping @Sendable () async -> Void) -> some View
The refreshable
modifier requires an asynchronous closure that's executed when the view needs to be refreshed. For most views, you'll need to manually trigger the refresh and provide a UI element if necessary. However, iOS List views automatically refresh when pulled down, showing a progress indicator during the process.
Let’s create a simple List view that displays data from a state variable containing a collection of strings. We’ll use the refreshable
modifier to update the state variable with new data fetched from an asynchronous function called fetchDataFromAPI
.
struct RefreshableListView: View {
@State private var data = [String]()
var body: some View {
NavigationStack {
List(data, id: \.self) { item in
Text(item)
}
.refreshable {
self.data = await fetchDataFromAPI()
}
.navigationTitle("DevTechie Courses")
}
}
func fetchDataFromAPI() async -> [String] {
return ["Mastering…