Show a page refresh in swiftui

Generated on 8/4/2024

1 search

To implement a page refresh in SwiftUI, you can use the refreshable modifier, which was introduced in iOS 15. This modifier allows you to add pull-to-refresh functionality to your views, such as List or ScrollView.

Here's a basic example of how to use refreshable in a SwiftUI view:

import SwiftUI

struct ContentView: View {
    @State private var items = ["Item 1", "Item 2", "Item 3"]

    var body: some View {
        NavigationView {
            List(items, id: \.self) { item in
                Text(item)
            }
            .refreshable {
                await fetchData()
            }
            .navigationTitle("Pull to Refresh")
        }
    }

    func fetchData() async {
        // Simulate a network call
        try? await Task.sleep(nanoseconds: 2 * 1_000_000_000)
        items.append("New Item")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

In this example:

  • The List displays a list of items.
  • The refreshable modifier is added to the List, which calls the fetchData function when the user pulls down to refresh.
  • The fetchData function simulates a network call by sleeping for 2 seconds and then adds a new item to the list.

For more detailed information on state-driven views and animations in SwiftUI, you can refer to the SwiftUI essentials session from WWDC 2024.