Pull to refresh in UICollectionView in ViewController

New swift code changed in calling action method you could do rewrite like this

@IBOutlet weak var collectionView: UICollectionView!

var refresher:UIRefreshControl!

override func viewDidLoad() {

   super.viewDidLoad()

    self.refresher = UIRefreshControl()
    self.collectionView!.alwaysBounceVertical = true
    self.refresher.tintColor = UIColor.red
    self.refresher.addTarget(self, action: #selector(loadData), for: .valueChanged)
    self.collectionView!.addSubview(refresher)
}

@objc func loadData() {
   self.collectionView!.refreshControl.beginRefreshing()
   //code to execute during refresher
       .
       .
       .
   stopRefresher()         //Call this to stop refresher
 }

func stopRefresher() {
   self.collectionView!.refreshControl.endRefreshing()
 }

Swift 5 solution

As @fishspy already mentioned, that's the way to put your collection view inside a view controller, but I'm gonna share also how to connect your refresh control to the collection view in a cleaner way.

Since iOS 10 there's a dedicated property for the refresh control. Apart of that, I'd also recommend to directly initialise your refresh control as a property, declaring it private and doing the following things:

@IBOutlet private weak var collectionView: UICollectionView!

private let refreshControl = UIRefreshControl()

override func viewDidLoad() {

    super.viewDidLoad()

    refreshControl.addTarget(self, action: #selector(didPullToRefresh(_:)), for: .valueChanged)
    collectionView.alwaysBounceVertical = true
    collectionView.refreshControl = refreshControl // iOS 10+
}

@objc
private func didPullToRefresh(_ sender: Any) {
    // Do you your api calls in here, and then asynchronously remember to stop the
    // refreshing when you've got a result (either positive or negative)
    refreshControl.endRefreshing()
}

Tags:

Ios

Swift