【问题标题】:create an empty section(header view) with no cell in core data在核心数据中创建一个没有单元格的空部分(标题视图)
【发布时间】:2020-03-23 05:07:08
【问题描述】:

我有两个实体。用户和属性。用户与属性具有一对一的关系,而属性与用户具有一对多的关系。 我正在使用 FRC(获取结果控制器并希望将“用户”实体用作部分(标题视图)并将属性用作表格视图单元格。 我希望能够添加没有单元格的用户部分(标题视图)。 但默认情况下,我每个新部分都有一个单元格。

这是 FRC 的代码:

 lazy var fetchResultController: NSFetchedResultsController<Attribute> = {
        let fetchRequest: NSFetchRequest<Attribute> = Attribute.fetchRequest()
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(Attribute.name), ascending: false)]

        let fetchResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.persistentContainer.managedContext, sectionNameKeyPath: #keyPath(Attribute.user.name), cacheName: nil)

        fetchResultController.delegate = self

        return fetchResultController
    }()

表格视图:

func numberOfSections(in tableView: UITableView) -> Int {
        guard let sections = fetchResultController.sections else {return 0}
        return sections.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard let section = fetchResultController.sections?[section] else{return 0}
        return section

    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ID.TableView.mainPage) as! AttributeCell
        let task = fetchResultController.object(at: indexPath)

        cell.nameLbl.text = task.name

        return cell
    }

【问题讨论】:

  • 你必须在cellForRowAtfunction 中添加一个新的部分和一个验证,如果你在最后一个部分只返回没有数据的单元格。
  • 由于属性和用户之间存在一对多的关系,因此属性必须是部分,而用户是该部分的行。还是您对模型的解释有误?

标签: ios objective-c swift uitableview core-data


【解决方案1】:

试试这个

var numberSections = 0
func numberOfSections(in tableView: UITableView) -> Int {
    guard let sections = fetchResultController.sections else {
      numberSections = 0
      return 0}
    numberSections = sections + 1
    return sections.count + 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    guard let section = fetchResultController.sections?[section] else{return 0}
    return section + 1

}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: ID.TableView.mainPage) as! AttributeCell
    let task = fetchResultController.object(at: indexPath)
      //4                //5
    if numberSections - 2 > indexPath.section
    {
       cell.nameLbl.text = task.name
    }
    else
    {
       cell.nameLbl.text = ""
    }

    return cell
}

这将创建一个空白部分,直到结束

【讨论】:

    猜你喜欢
    • 2011-01-27
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 2019-09-26
    • 1970-01-01
    • 2017-02-22
    相关资源
    最近更新 更多