[go: up one dir, main page]

DEV Community

Wesley de Groot
Wesley de Groot

Posted on • Originally published at wesleydegroot.nl on

Pull-to-Refresh in SwiftUI

Pull-to-refresh is a common UI pattern in iOS apps.

It allows users to refresh the content of a view by pulling down on it.

In this post, we will learn how to implement pull-to-refresh in SwiftUI, using the refreshable modifier.

What is Pull-to-refresh?

Pull-to-refresh is a common UI pattern in iOS apps that allows users to refresh the content of a view by pulling down on it.

Use Case: Pull to refresh

Let’s start with a simple example where you have a List displaying items.

It should also provide a pull-to-refresh gesture to update the list of items.

import SwiftUI

struct ContentView: View {
    @State private var items = [String](repeating: "Item", count: 10)

    var body: some View {
        List {
            ForEach(items, id: \.self) { item in
                Text(item)
            }
        }
        .refreshable {
            items = [String](repeating: "Refreshed items", count: 10)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Download the sample code for Swift Playgrounds

In the example above, we attach the refreshable view modifier to the List view, configuring the pull-to-refresh gesture.

Wrap up

SwiftUI's refreshable modifier makes it easy to add pull-to-refresh to your app.

Conclusion

In this post, we learned how to implement pull-to-refresh in SwiftUI, using the refreshable modifier.

Resources:

Top comments (0)