【问题标题】:Programmatically assigning datasource to UITableView not calling datasource method以编程方式将数据源分配给 UITableView 而不调用数据源方法
【发布时间】:2019-05-13 14:35:24
【问题描述】:

我有tableview 有两个部分,每个部分有一排。 我想在单击按钮时填写tableview 数据。 在viewDidLoad 我隐藏tableView。 单击按钮时,我将datasourcedelegate 分配给tableview 并取消隐藏tableview,但它的datasource 方法没有被调用。

下面是代码:

@IBAction func btnShowAction(_ sender: Any) {

    tableView.delegate = self
    tableView.dataSource = self
    tableView.isHidden = false
}

func numberOfSections(in tableView: UITableView) -> Int {

    return 2
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return 1
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return ((tableView.frame.size.height / 2) - 20)
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    if(section == 0) {

        return "Section 1"
    }
    else {

        return "Section 2"
    }
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

    return 20
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let tableViewCell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
    tableViewCell.lblText.text = "abc"
    return tableViewCell
}

【问题讨论】:

  • 为什么要在按钮操作中设置数据源和委托?
  • 如果需要,我想根据用户请求在tableview中填写数据
  • 彻坦,你需要重新加载你的tableview,如果你想将你更新的数据显示到TableView
  • 这不合理。
  • @abdul 它不会在我设置数据源时自动重新加载数据?

标签: ios swift uitableview datasource


【解决方案1】:

当视图加载时,例如viewDidLoad(),此时数据源方法将在内部调用reloadData(),但在您单击按钮的情况下,我们需要显式调用reloadData() 以更新表视图,因为视图已经加载.你的代码应该是这样的,

@IBAction func btnShowAction(_ sender: Any) {

    tableView.delegate = self
    tableView.dataSource = self
    tableView.reloadData()
    tableView.isHidden = false
}

这会重新加载表格视图的行和部分。希望对您有所帮助。

【讨论】:

  • 为什么需要tableView.reloadData()?
  • reloadData() 方法重新加载用于构建表格的所有数据,包括单元格、节页眉和页脚、索引数组。您可能想参考,developer.apple.com/documentation/uikit/uitableview/…
  • 设置数据源后不会自动重新加载section的行
  • 根据 Apple 的文档,表视图的委托或数据源在希望表视图完全重新加载其数据时调用 reloadData 方法
  • tableView.dataSource = self 执行数据的初始加载。你不需要在设置后直接调用 reload 。当数据发生变化时使用重新加载
猜你喜欢
  • 2011-03-23
  • 2012-12-06
  • 2010-12-10
  • 1970-01-01
  • 2011-07-13
  • 1970-01-01
  • 2013-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多