[Swift in Xcode]UITableView pull to refresh

2016-01-09

Sometimes when we are writing forum for an App, we may face with that when want the user to pull down the tableView and then, it can refresh the UITableView automatically to present the latest posts. Luckily, there is a very convenient way to do it.:-)

Firstly, we need to define a UIRefreshControl, like:

1
var refreshControl = UIRefreshControl()

Then, add a target for that control by:

1
2
3
refreshControl.tintColor = UIColor.whiteColor()
refreshControl.addTarget(self, action: "refresh:", forControlEvents: .ValueChanged)
tableView.addSubview(refreshControl)

The tintColor is for change the color of the activity indicator. Then function refresh is what we need to implement when the user scroll down the tableView, here is an example:

1
2
3
4
func refresh(refreshControl: UIRefreshControl){
self.getTopicFromMYSQL()
refreshControl.endRefreshing()
}

It is very important to add refreshControl.endRefreshing(), because, when the implementation is finished, the activity indicator should disappear.


Comments: