iosswiftxcodeuirefreshcontrol

How to use pull-to-refresh in Swift?


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 behavior of Gesture recognizers. A working sample code will be a great help.

Thanks.


Solution

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

    let refreshControl = UIRefreshControl()
    
    override func viewDidLoad() {
       super.viewDidLoad()
    
       refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
       refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .valueChanged)
       tableView.addSubview(refreshControl) // not required when using UITableViewController
    }
    
    @objc func refresh(_ sender: AnyObject) {
       // Code to refresh table view  
    }
    

    At some point you could end refreshing.

    refreshControl.endRefreshing()