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?
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:
You do not have to use semicolons anymore :-).
Refresh control and the refresh control selector can not have the same name (i.e. action: "refresh").
There is no "self.refreshControl = refresh;".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With