xrage xrage - 5 months ago 32
iOS Question

How to use pull to refresh in swift 2

I am building an RSS reader using swift and need to implement pull to reload functionality.

Here is how i am trying to do it.

class FirstViewController: UIViewController,
UITableViewDelegate, UITableViewDataSource {

@IBOutlet var refresh: UIScreenEdgePanGestureRecognizer
@IBOutlet var newsCollect: UITableView

var activityIndicator:UIActivityIndicatorView? = nil

override func viewDidLoad() {
super.viewDidLoad()
self.newsCollect.scrollEnabled = true
// Do any additional setup after loading the view, typically from a nib.

if nCollect.news.count <= 2{
self.collectNews()
}
else{
self.removeActivityIndicator()
}
view.addGestureRecognizer(refresh)
}



@IBAction func reload(sender: UIScreenEdgePanGestureRecognizer) {
nCollect.news = News[]()
return newsCollect.reloadData()
}


I am getting :


Property 'self.refresh' not initialized at super.init call


Please help me to understand the behaviour of Gesture recognisers. A working sample code will be a great help.

Thanks.

Answer

Pull to refresh is built in iOS. You could do this in swift like

var refreshControl: UIRefreshControl!

override func viewDidLoad() {
   super.viewDidLoad()

   refreshControl = UIRefreshControl()
   refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
   refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
   tableView.addSubview(refreshControl) // not required when using UITableViewController
}

func refresh(sender:AnyObject) {
   // Code to refresh table view  
}

At some point you could end refreshing.

refreshControl.endRefreshing()
Comments