【问题标题】:Separating UITableViewDelegate and UITableViewDataSource Causes No Data to Show分离 UITableViewDelegate 和 UITableViewDataSource 导致没有数据显示
【发布时间】:2016-05-28 07:36:52
【问题描述】:

由于 UITableViewDelegate 和 UITableViewDataSource 所需的所有方法,我的 ViewController 变得太大了,所以我将代码重构到不同的文件,但现在数据不再显示...

这是我当前的实现:

在 MyViewController.swift 中

class SomeView: UIViewController {

  @IBOutlet weak var myTableView: UITableView!

  override func viewDidLoad() {
     super.viewDidLoad()
     myDataSourceClass(tableView: myTableView)
  }
}

在 MyNewDataSourceClass.swift 中

class myDataSourceClass: UITableViewDelegate, UITableViewDataSource {
  let stuff = [1, 2, 3]
  init(tableView: UITableView) {
        super.init()
        tableView.delegate = self
        tableView.dataSource = self
  }
  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell")
        cell?.textLabel?.text = "please show up"
        return cell!
  }
  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.stuff.count
  }
}

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 在单独的文件而不是类中创建SomeView 的扩展名要容易得多。失败的原因是您正在初始化数据源类,但它在viewDidLoad 退出后立即被释放
  • 您是否将 myDataSourceClass 引用保存在某处?
  • @orxelm 我很遗憾没有...我应该把它放在哪里以及如何使用该参考?
  • @vadian 这是有道理的。我将尝试创建一个扩展来看看它是如何进行的。除了 View 代码不会变得臃肿之外,与我一样创建扩展与类相比,还有其他内在的好处吗?
  • @LongTran 我猜这就是你的问题。尝试添加对 myDataSourceClass 的强引用并检查。 var myDataSourceClass: MyDataSourceClass 在 myTableView @IBOutlet 声明下方。

标签: ios swift uitableview


【解决方案1】:

//设置委托和数据源后需要重新加载表

class SomeView: UIViewController {

  @IBOutlet weak var myTableView: UITableView!

 override func viewDidLoad() {
    super.viewDidLoad()
    myDataSourceClass(tableView: myTableView)
    myTableView.reloadData()
 }
}

【讨论】:

  • 我在发布问题之前尝试过,但我认为这不是问题所在。
  • 然后检查 self.stuff.count 并检查 tableview 与 reference 的连接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-25
  • 2020-04-08
相关资源
最近更新 更多