How do I handle pull-to-refresh in UIKit with Swift?

To handle pull-to-refresh functionality in UIKit with Swift, you can utilize the UIRefreshControl class, which offers a simple way to implement this feature in table views or collection views. Here's how you can set it up:

import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let tableView = UITableView() let refreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() setupTableView() setupRefreshControl() } func setupTableView() { tableView.dataSource = self tableView.delegate = self tableView.frame = view.bounds view.addSubview(tableView) } func setupRefreshControl() { refreshControl.addTarget(self, action: #selector(refreshData), for: .valueChanged) tableView.refreshControl = refreshControl } @objc func refreshData() { // Add your data refreshing logic here // Simulating a network call with a delay DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self.refreshControl.endRefreshing() // Update your data source and reload the table view self.tableView.reloadData() } } // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 // example static count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = "Row \(indexPath.row + 1)" return cell } }

pull-to-refresh UIRefreshControl UITableView Swift UIKit