pull to refresh

Aug 30, 2021 swiftui

How Can we implement Pull to refresh in SwiftUI

Table of Contents

Pull to Refresh in SwiftUI

Earlier in storyboard we were used to UIRefreshControl() which was using this observer we would load the tableview by calling the tableViewreloadata()

let refreshControl = UIRefreshControl()




override func viewDidLoad() {

   super.viewDidLoad()




   refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")

   refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .valueChanged)

   tableView.addSubview(refreshControl) // not required when using UITableViewController

}




@objc func refresh(_ sender: AnyObject) {

   // Code to refresh table view

}

But as SwiftUI has been introduce by apple in WWDC 2020 we needed to reload the list in swiftUI we use the code Refreshable() the below code can be used as pull to refresh the list in SwiftUI

import SwiftUI

struct ContentView: View {

    var body: some View {

        NavigationView {

            List(1..<10) { row in

                Text("Row No (row)")

            }.refreshable {

                print("Do your refresh work here")

            }

        }

    }

}

by above we can refresh the list of the iOS application. Now iOS is automatically show the activity loader when we refresh the screen

Here is the output of the Pull to refresh in SwiftUI

 

Table of Contents

Index