【问题标题】:UITableViewController with custom data source not showing cells具有自定义数据源的 UITableViewController 不显示单元格
【发布时间】:2016-07-05 19:35:50
【问题描述】:

我目前有一个 UITableViewController,它在它的 init 函数中设置了一个自定义数据源:

class BookmarkTableViewController: UITableViewController {
  var date: Date

  // MARK: - Init
  init(date: Date, fetchAtLoad: Bool) {
    self.date = date
    super.init(style: .plain)
    self.tableView.dataSource = BookmarkDataSource(date: date)
    self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
  }

// ...
}

自定义数据源如下:

class BookmarkDataSource: NSObject {
  let date: Date

  init(date: Date) {
    self.date = date
    super.init()
  }
}

// MARK: - UITableViewDataSource
extension BookmarkDataSource: UITableViewDataSource {
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 3
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.text = "Test content"

    return cell
  }
}

但是,当我在模拟器或设备上运行时,表格视图中没有显示任何内容。有谁知道我错过了什么?

注意:我使用的是 Xcode 8.0 Beta 和 Swift 3。

【问题讨论】:

    标签: ios swift uitableview swift3 xcode8


    【解决方案1】:

    您需要存储对 BookmarkDataSource 对象的强引用。 tableView 的数据源随着您发布的代码变为 nil。

    class BookmarkTableViewController: UITableViewController {
        var date: Date
        var dataSource:BookmarkDataSource
    
        // MARK: - Init
        init(date: Date, fetchAtLoad: Bool) {
            self.date = date
            super.init(style: .plain)
            dataSource = BookmarkDataSource(date: date)
            self.tableView.dataSource = dataSource
            self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        }
    
        // ...
    }
    

    【讨论】:

    • 是的!就是这个。谢谢!
    • 我搞砸了 dataSource 变量的创建,但你明白了!
    【解决方案2】:

    我认为您的单元格没有被正确实例化。

    尝试替换

    let cell = UITableViewCell()
    

    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
    

    【讨论】:

    • 这也是非常重要的,为了减少内存消耗并真正利用 UITableView。然而,这不是数据不显示的原因
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    相关资源
    最近更新 更多