Search code examples
iosswiftuitableviewreloaddata

UITableView reloadData() from ViewController with extension of UITableViewDataSource, UITableViewDelegate


I worked my table view with an extension to the ViewController.

How can I use reloadData() as in TableViewController?

extension ViewController: UITableViewDataSource, UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return articles.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let a = articles[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "articleCell", for: indexPath) as! ArticleTableViewCell
        cell.titleLabel.text = a.title

        return cell
    }  
}

Solution

  • Firstly, wherefrom data coming into articles array if data is static meaning you defining in your code then you simply create an outlet for tableView and use self.tableView.reloadData in viewDidLoad and if your data is coming from api then you can use this code

         ` DispatchQueue.main.async {
                self.tableview.reloadData()
            }`
    

    after you parsing your data into data