创建一个空部分(标题视图),核心数据中没有单元格



我有两个实体。 用户和属性。 用户与属性具有一对一关系,属性与用户具有一对多关系。 我正在使用 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
}

试试这个

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
}

这将创建一个空部分,直到最后

最新更新