Pull down to refresh in SwiftUI

In this SwiftUI tutorial, we’ll learn how to refresh the content of a list and how to customize the refresh spinner.

What this blog will cover:

  • How to implement pull-to-refresh functionality in SwiftUI.
  • How to customize the refresh spinner.

Let’s get started.

First of all, we’ll implement a simple List view in the main view, ContentView of the App.

struct ContentView: View{
    var body: some View{
        List(1..<10) { row in
            Text("Row \(row)")
        }
    } 
}

 

Now, for implementing the pull to refresh functionality all we have to do is to call a refreshable modifier of the List view. It will do all the work for us. In the closure of the modifier, we can perform any task whenever the user refreshes the list.

 

struct ContentView: View{
    var body: some View{
        List(1..<10) { row in
            Text("Row \(row)")
        }
       
        .refreshable {
            print("Perform any task here")
        }
     }
 }

 

Pull down to refresh in SwiftUI

Customizing the refresh spinner

So now for the customization part, we can change the tint color of the spinner and we can also give it a label.

Let’s change the tint color of the spinner first.

struct ContentView: View{
    var body: some View{
        List(1..<10) { row in
            Text("Row \(row)")
        }
       
        .refreshable {
            print("Perform any task here")
        }
        .onAppear {
            UIRefreshControl.appearance().tintColor = .cyan
        }
        
    }
        

We have changed the tintColor of the spinner in the .onAppear method.

The onAppear method will be called as soon as the user refreshes the list and a spinner appears on the screen.

So when the spinner appears on the screen, the .onAppear method will change the color of the spinner.

 

In a similar manner, we’ll give a label or title to the spinner in the .onAppear method.

 

struct ContentView: View{
    var body: some View{
        List(1..<10) { row in
            Text("Row \(row)")
        }
       
        .refreshable {
            print("Perform any task here")
        }
        .onAppear {
            
            UIRefreshControl.appearance().tintColor = .cyan
            UIRefreshControl.appearance().attributedTitle = NSAttributedString("Refreshing…")

        }
        
    }
}

 

Pull down to refresh in SwiftUI

 

Leave a Reply

Your email address will not be published. Required fields are marked *