Refreshable
Liang Wang
Posted on January 30, 2024
Apple documentation
https://developer.apple.com/documentation/swiftui/view/refreshable(action:)
Apply this modifier to a view to set the refresh value in the view’s environment to a RefreshAction instance that uses the specified action as its handler. Views that detect the presence of the instance can change their appearance to provide a way for the user to execute the handler.
For example, when you apply this modifier on iOS and iPadOS to a List, the list enables a standard pull-to-refresh gesture that refreshes the list contents. When the user drags the top of the scrollable area downward, the view reveals a progress indicator and executes the specified handler. The indicator remains visible for the duration of the refresh, which runs asynchronously:
List(mailbox.conversations) { conversation in
ConversationCell(conversation)
}
.refreshable {
await mailbox.fetch()
}
Refreshing custom views
You can also offer refresh capability in your custom views. Read the refresh environment value to get the RefreshAction instance for a given Environment. If you find a non-nil value, change your view’s appearance or behavior to offer the refresh to the user, and call the instance to conduct the refresh. You can call the refresh instance directly because it defines a callAsFunction() method that Swift calls when you call the instance:
struct RefreshableView: View {
@Environment(\.refresh) private var refresh
var body: some View {
Button("Refresh") {
Task {
await refresh?()
}
}
.disabled(refresh == nil)
}
}
Posted on January 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024