如何让Dynamic TableViewDataSource更新表视图?

时间:2017-11-28 09:30:45

标签: ios swift

我发现Google使用的模式使IOS SDK变得干净且设计得很好。基本上他们遵循以下苹果演示文稿中的内容:Advanced User interface with Collection view(它开始幻灯片46)。

这是他们的GMSAutocompleteTableDataSource中实现的内容。 我们直到数据源来定义tableview的状态。 我们链接了tableview。

var googlePlacesDataSource = GMSAutocompleteTableDataSource()
tableView.dataSource = googlePlacesDataSource
tableView.delegate = googlePlacesDataSource

然后,每次更改事件时,都会绑定到数据源:

googlePlacesDataSource.sourceTextHasChanged("Newsearch")

数据源执行查询,将表视图设置为加载,然后显示结果。

我想从我的自定义来源实现这一点:

class JourneyTableViewDataSource:NSObject, UITableViewDataSource, UITableViewDelegate{
   private var journeys:[JourneyHead]?{
        didSet{
         -> I want to trigger tableView.reloadData() when this list is populated... 
         -> How do I do that? I do not have a reference to tableView?
        }
   }

    override init(){
        super.init()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    ...
}

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您的数据源不应知道关于您的表格视图的任何。这是这种模式的基础,它在可重用性方面为您提供了很多功能。

出于您的目的,最佳解决方案是使用属性闭包:

var onJourneysUpdate: (() -> Void)?

private var journeys: [JourneyHead]? {
    didSet {
        onJourneysUpdate?()
    }
}

在设置数据源时,您可以设置在更新数据源阵列后要执行的任何操作:

var googlePlacesDataSource = JourneyTableViewDataSource()
tableView.dataSource = googlePlacesDataSource
tableView.delegate = googlePlacesDataSource
googlePlacesDataSource.onJourneysUpdate = { [unowned self] in
    self.tableView.reloadData()
}

答案 1 :(得分:0)

要更新动态tableview,您必须添加reloadDatareloadData更新数据源。

self.tableview.reloadData()
相关问题