Search code examples
iosswiftuitableviewuirefreshcontrol

How to implement refresh control for table views as common function


I've many VCs in which I've Table Views where I add refresh control. It's a copy paste in each VC. I wanted to move refresh control to a common function in extension but I can't figure out how to do it. If there is any other way to avoid copy n paste then please give me some pointers.

Following is my typical refresh control implementation in a VC.swift

class MyVC: UIViewController {

    lazy var refreshControl: UIRefreshControl = {
        let refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: #selector(refresh(_:)), for: UIControlEvents.valueChanged)
         return refreshControl
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        if #available(iOS 10.0, *) {
            messagesTable.refreshControl = refreshControl
        } else {
            messagesTable.addSubview(refreshControl)
       }
    }

    @objc func refresh(_ refreshControl: UIRefreshControl) {
        fetchData()
    }
}

Solution

  • If all of your ViewController should has TableView as well as RefreshControl inside, you can create one superclass (you can keep MyVC) for all of these Controllers.

    class MyVC: UIViewController {
    
        lazy var refreshControl: UIRefreshControl = {
            let refreshControl = UIRefreshControl()
            refreshControl.addTarget(self, action: #selector(refresh(_:)), for: UIControlEvents.valueChanged)
            return refreshControl
        }()
    
        func addRefreshControl(to tableView: UITableView) {
            if #available(iOS 10.0, *) {
                tableView.refreshControl = refreshControl
            } else {
                tableView.addSubview(refreshControl)
            }
        }
    
        @objc func refresh(_ refreshControl: UIRefreshControl) {
            fetchData()
        }
    
        func fetchData() {
        }
    }
    

    then make your other Controllers subclasses of MyVC and when you need to add RefreshControl, call addRefreshControl with controller's TableView as parameter

    class MessageVC: MyVC {
    
        @IBOutlet weak var messageTable: UITableView!
        ...
        override func viewDidLoad() {
            super.viewDidLoad()
            ...
            addRefreshControll(to: messageTable)
        }
        ...
        override func fetchData() {
            // what should happen when refresh control changes its value
        }
    }
    

    ... also you can override fetchData method and declare what should happen when refresh control changes its value