I am coding an app and have a set up queryAndAppend functions that query a DB and append the info pulled to a set of arrays (which are then used to iterate through cells in a table view). The query functions work appropriately as they are called in the viewDidLoad()
. I want a pull to refresh function to additionally call the functions (and thus update the table cells) but it is not working properly. Here is the relevant code:
var refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
myQueryandAppend(completion: {
self.tableView.reloadData()
})
upComingQueryandAppend(completion: {
self.tableView.reloadData()
})
refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: #selector(MainPageVC.refresh(_:)), for: UIControlEvents.valueChanged)
}
func refresh(_ sender: AnyObject){
myQueryandAppend(completion: {
self.tableView.reloadData()
self.refreshControl.endRefreshing()
})
upComingQueryandAppend(completion:{
self.tableView.reloadData()
self.refreshControl.endRefreshing()
})
}
Not entirely sure why its not working as I have a very similar set up in a different view controller (with a different query/append function) that works properly with pull to refresh.
If the class is a UIViewController
but not a UITableViewController
, you need to add the refreshControl
as a subview to the tableView
manually:
tableView.addSubview(refreshControl)
So, viewDidLoad()
should looks like this:
override func viewDidLoad() {
super.viewDidLoad()
myQueryandAppend(completion: {
self.tableView.reloadData()
})
upComingQueryandAppend(completion: {
self.tableView.reloadData()
})
refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: #selector(MainPageVC.refresh(_:)), for: UIControlEvents.valueChanged)
// here is the extra job!
tableView.addSubview(refreshControl)
}