RefreshControl with software UITableView without UITableViewController

I created my UITableView instance programmatically and added it to the root view as a submatrix. I also set the delegate and dataSource for the table view instance programmatically. Therefore, there is no table view controller in this table view. Now I want the table view to be available for updating. I learned the code from Google, for example:

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

Now the question is: selfrefers to the table view controller. However, in this context, I do not have a table view controller. So should I create a table view controller only to implement the pull down to refresh function?

+4
source share
1 answer

You can do it as follows:

// 1: add the instance variable to your ViewController.

let refreshControl = UIRefreshControl()

// 2: In viewDidLoad () configure update control

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

// 3: And (still in viewDidLoad ()) adds it as a subview in tableView (UITableView)

tableView.addSubview(refreshControl)

// 4: Finally, in your refresh (): function, be sure to finish updating this control.

refreshControl.endRefreshing()

// Remember that this (end of update) should be done in the main queue! “If you are not there.” In this case, you can use something like:

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

Notes for your code:

  • You no longer need to use semicolons :-).

  • The update control and the update control selector cannot have the same name (for example, the action: "update").

  • No "self.refreshControl = refresh;".

+8

All Articles