Pull to Refresh UIViewController in iOS

If you try to add a UIRefreshControl to a UIViewController, you’ll get an error.

UIRefreshControl can only be managed by a UITableViewController.

So, here’s a trick.

Code

  1. Set up a table view in your UIViewController.
1
2
let refreshControl = UIRefreshControl()
var tableView = UITableView()
  1. Add refreshControl to tableView, not view.
1
2
3
4
5
6
tableView.frame = view.frame

refreshControl.addTarget(self, action: Selector("refreshView:"), forControlEvents: .ValueChanged)
tableView.addSubview(refreshControl) // here it is

self.view.addSubview(tableView)
  1. refreshView function.
1
2
3
4
5
6
func refreshView(refreshControl: UIRefreshControl) {
refreshControl.attributedTitle = NSAttributedString(string: "Refresh")
refreshControl.attributedTitle = NSAttributedString(string: "Last updated on " + NSDate().description)

refreshControl.endRefreshing()
}

If you, like me, prefer to use Storyboard

  1. Storyboard -> UITableViewController -> enable Refreshing.

  2. Then you can Ctrl + drag just like UIButton.

Translated by gpt-3.5-turbo