【问题标题】:Using UITableView with storyboard but separate datasource将 UITableView 与情节提要但单独的​​数据源一起使用
【发布时间】:2014-11-12 02:09:52
【问题描述】:

编辑在这篇文章下面回答

我正在尝试在情节提要中设置一个 UITableView 控制器,使用单独的数据源,但我碰壁了。数据源似乎没有响应更改或将其“更新”推送到表视图。我已经尝试在 MainMenuTableViewController 中实现数据源,效果很好。

这是我的 MainMenuTableViewController

override func viewDidLoad() {
    super.viewDidLoad()

    sharedLightsManager.delegate = self
    sharedLightsManager.loadNetworkContext()

    dataSource = MainMenuTableViewDataSource(sharedLightsManager: sharedLightsManager)
    tableView.dataSource = dataSource
    tableView.delegate = dataSource

    title = "test"

}
//This method fires each time a change happens
func updateLights(){
    lights = sharedLightsManager.localNetworkContext.allLightsCollection.lights
    tableView.reloadData()
}

MainMenuDataSource:

class MainMenuTableViewDataSource: NSObject, UITableViewDataSource, UITableViewDelegate
{
    let reuseIdentifier = "tableViewCell"
    var sharedLightsManager: SharedLightsManager?
    var lights = []

    init(sharedLightsManager: SharedLightsManager)
    {
        self.sharedLightsManager = sharedLightsManager
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return lights.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("tableViewCell", forIndexPath: indexPath) as UITableViewCell
        var lights = sharedLightsManager!.localNetworkContext.allLightsCollection.lights
        var light = LFXLight()
        if lights.count == 0 {
        println("Lights array still loading...")
        } else {
            light = lights[indexPath.row] as LFXLight
        }
        return cell
    }

}

这是我的分店:

我刚刚想通了。有点尴尬。这是由于 lights 数组中没有任何对象,所以 obv。 lights.count 将返回 0,因此没有行...

【问题讨论】:

    标签: ios uitableview swift datasource


    【解决方案1】:

    除非通知 UITableView 重新加载数据,否则数据源不会推送更新。如果更改 numberOfRows 值,除非通过 insertRowAtIndexPath、reloadData、deleteRowAtIndexPath 等方法通知 tableView,否则它不会更新。

    【讨论】:

    • 抱歉,我应该提到我确实有一个 reloadData 调用,它会在更新发生时触发。我已将其添加到问题中。
    • 嗯,所以您根本看不到任何行?
    • 我刚刚弄明白了。有点尴尬。这是由于 lights 数组中没有任何对象,所以 obv。 lights.count 将返回 0,因此没有行...抱歉浪费您的时间..!
    • 别担心,恭喜你搞定了!希望您的(我猜的)HomeKit 应用程序运行良好!
    • 谢谢!这是 LIFX 灯泡的应用程序 :)
    猜你喜欢
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多