Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

refreshControl with programatic UITableView without UITableViewController

I created my UITableView instance programmatically, and added it to the root view as a sub view. I also set the delegate and dataSource for the table view instance programatically. So this table view does not have a table view controller. Now I want to make the table view be able to pull down to refresh. I learned some code from Google, like so:

var refresh = UIRefreshControl();
refresh.attributedTitle = NSAttributedString(string: "Pull to refresh");
refresh.addTarget(self, action: "refresh", forControlEvents:.ValueChanged);
self.refreshControl = refresh;

Now, the question is the self refers to the table view controller. However, in this context, I don't have a table view controller. So do I have to create a table view controller just in order to implement the pull down to refresh function?

like image 765
Qian Chen Avatar asked Sep 27 '14 05:09

Qian Chen


1 Answers

You can do this in the following way:

//1: Add an instance variable to your ViewController.

let refreshControl = UIRefreshControl()

//2: In viewDidLoad() set up your refresh control

refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)

//3: And (still in the viewDidLoad()) add it as a subview to the tableView (UITableView)

tableView.addSubview(refreshControl)

//4: Finally, in your refresh() function: do not forget to end the refreshing of this control.

refreshControl.endRefreshing()

// Be aware, this (end of refreshing) must be done on the main queue! - if you are not there. In such case you might use something like:

dispatch_async(dispatch_get_main_queue()) {
   self.tableView.reloadData()
   self.refreshControl.endRefreshing()
 }

Remarks to your code:

  1. You do not have to use semicolons anymore :-).

  2. Refresh control and the refresh control selector can not have the same name (i.e. action: "refresh").

  3. There is no "self.refreshControl = refresh;".

like image 152
StanislavK Avatar answered Sep 19 '22 14:09

StanislavK