Search code examples
iosswiftuikitscrollviewrefresh

How to call function when collection view is reloaded?


I have a collection view and want to run some things when it is reloaded by the user. This reloading is caused by the user dragging down on the view until the reload icon comes out. Putting this function at anything else other than when the user does an interaction to reload the collection, will make this an unfeasible solution for me.


Solution

  • What about the following solution. I implemented it for collection-, table- and scroll views, in case other people have similar issues:

    final class ScrollViewRefreshDemo: UIViewController {
    
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
        let tableView = UITableView()
        let scrollView = UIScrollView()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            attachRefreshListener(to: collectionView)
            attachRefreshListener(to: tableView)
            attachRefreshListener(to: scrollView)
        }
    
        func attachRefreshListener(to scrollView: UIScrollView) {
            scrollView.refreshControl?.addTarget(self, action: #selector(scrollViewDidRefresh), for: .valueChanged)
        }
    
        @objc
        func scrollViewDidRefresh() {
    
            // Execute any task while the scroll view is refreshing
        }
    }