【问题标题】:Why headerView is always nil in numberOfRowsInSection?为什么 headerView 在 numberOfRowsInSection 中总是为零?
【发布时间】:2021-03-19 21:17:31
【问题描述】:

我必须为一个满足条件的表创建一个动态数据源:

  • 我们不知道确切的节数
  • 我们不知道部分标题的确切标题
  • 我们现在不知道每次在每个部分中有多少行

要检测每个部分的行数,我有以下代码:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let header = tableView.headerView(forSection: section)
        return self.servicesData?.filter({ $0.clubName == header?.textLabel?.text }).count ?? 0
    }

其中servicesData 是要由标题标题(又名clubName)过滤的对象数组。标题是从对象数组中收集的。

由于某种原因,我在尝试访问标头时总是得到nil。到目前为止,我尝试直接在numberOfRowsInSection 中调用tableView(_:titleForHeaderInSection:),但显然没有运气。

非常感谢您的反馈。

【问题讨论】:

  • 必填,你设置委托了吗?
  • 当然是@CSmizzle(如果你的意思是self.servicesTableView.delegate = self self.servicesTableView.dataSource = self
  • 在获得serviceData 的完整列表后,您是否致电tableView.reloadData()
  • @Andrew 是的,我在从 API 下载新的 serviceData 数组后立即调用此方法
  • 你能发布你的 cellForRowAt 函数吗?

标签: ios swift uitableview uikit


【解决方案1】:

它是 nil,因为它不是在那一刻创建的。你不应该在numberOfRows 中使用tableView.headerView(forSection: section)。您应该使用从中获得标题的模型来使用它来过滤数组。

您应该先获取所有数据,然后再填充表格视图。那么你应该实现:

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

其中 headerModels 是带有您的标题的对象数组,它的项目如下:

class HeaderModel {
   let title: String
   let items: [YourItem]
}

然后:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return headerModels[section].items.count
}

【讨论】:

  • 谢谢!这解决了问题。然而,在实施您的解决方案时,我想到数据源可以以另一种方式传递。我会在下面描述。
【解决方案2】:

因此,根据@shurtugal 的解决方案,可以传入一个对象数组来填充表格。我认为为这种情况创建一个实用程序类可能太多了。所以这里是稍微改变的方式:

考虑一个字典var servicesData = [String: [CustomObject]](),每次出现 ViewController 时都会填充它。字典可以有不定数量的键和每个键内不定数量的值。填充字典的算法取自this的答案。

因此,UITableViewDatasource 方法可以这样定义:

func numberOfSections(in tableView: UITableView) -> Int {
        self.servicesData.count
    }
    
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Array(self.servicesData.values)[section].count
    }
    
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        /* cell creation code code */
        
        /// sample line 
        cell?.someLabel.text = Array(self.servicesData.values)[indexPath.section][indexPath.row]
        
        return cell
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    相关资源
    最近更新 更多