How to access and refresh a UITableView from another class in Swift

后端 未结 4 589
清歌不尽
清歌不尽 2021-01-03 09:24

I have a tab bar application and a tab whose view controller is controlled by a UITableView class. I have a class that is used to download data from the server that then sav

4条回答
  •  难免孤独
    2021-01-03 10:22

    There are many ways you can do this. The most standard way is to use delegation. Delegation is a very common pattern in iOS, you are using it with UITableViewDataSource. Your view controller is the delegate of the UITableView, meaning it conforms to the UITableViewDataSource protocol. So what you should do is create a protocol for your Updates class like this:

    protocol UpdatesDelegate {
        func didFinishUpdates(finished: Bool)
    }
    

    Your Updates class would have a delegate property that conforms to this protocol:

    class Updates {
        var delegate: UpdatesDelegate?
    

    Then you put this line where the //indicates progress finished comment was:

    self.delegate?.didFinishUpdates(finished: true)
    

    Your ConnectTableViewController would conform to the protocol and reload the table view from there:

    extension ConnectTableViewController: UpdatesDelegate {
        func didFinishUpdates(finished: Bool) {
            guard finished else {
                // Handle the unfinished state
                return 
            }
            self.tableView.reloadData()
        }
    }
    

    Where ever you created your instance of the Updates class, be sure to set the delegate property to your ConnectTableViewController.

    P.S. Your classes need to start with an uppercase letter. I've edited your question to reflect this.

提交回复
热议问题