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

In UIKit, adding pull-to-refresh functionality to a list can significantly enhance user experience by allowing users to refresh the content easily. This is commonly achieved using the `UIRefreshControl` class, which can be added to a `UITableView` or `UICollectionView`. Below is a simple example illustrating how to implement this feature in Swift.

// Swift code to add pull-to-refresh to a UITableView import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var tableView: UITableView! var data: [String] = ["Item 1", "Item 2", "Item 3"] override func viewDidLoad() { super.viewDidLoad() tableView = UITableView(frame: self.view.bounds) tableView.dataSource = self tableView.delegate = self self.view.addSubview(tableView) // Initialize UIRefreshControl let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refreshData(_:)), for: .valueChanged) tableView.refreshControl = refreshControl } @objc private func refreshData(_ sender: UIRefreshControl) { // Simulating data refresh DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self.data.append("New Item \(self.data.count + 1)") self.tableView.reloadData() sender.endRefreshing() } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: "cell") cell.textLabel?.text = data[indexPath.row] return cell } }

Pull-to-refresh UIKit Swift UITableView UIRefreshControl iOS development