使用支持NSFetchedResultsController展开/折叠UITableView部分

时间:2016-04-08 19:33:05

标签: ios uitableview core-data

    let frc = NSFetchedResultsController(
        fetchRequest: alertsFetchRequest,
        managedObjectContext: self.moc,
        sectionNameKeyPath: "formattedDateDue",
        cacheName: nil)

当我使用NSFetchedResultsController对记录进行分区时,如何展开和折叠表格视图中的部分?

我已经看到很多教程解释了扩展和折叠单元格本身,但没有解释使用获取结果控制器生成的部分。

2 个答案:

答案 0 :(得分:0)

如果要更改结果集,则需要更改请求中的谓词并再次调用performFetch()。然后,您可以更新您的表格。但是,这可能会导致性能问题。您可以考虑使用其他更复杂的技术来管理模型视图绑定,例如为每个扩展的部分设置不同的获取结果控制器。当用户展开一个部分时,创建一个新的获取结果控制器,只获取该部分的对象并更新表视图。当用户折叠该部分时,丢弃获取结果控制器。但是,这可能会使表视图数据源实现变得相当复杂。

答案 1 :(得分:0)

雨燕4:

这是pbasdf的Swift 4版本的绝佳解决方案:

定义和填充布尔数组:

sectionExpandedInfo = []
   for _ in _fetchedResultsController!.sections! {
      sectionExpandedInfo.append(true)
   }

numberOfRowsInSection方法:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if sectionExpandedInfo[section] { // expanded
            let sectionInfo = self.fetchedResultsController.sections![section] as NSFetchedResultsSectionInfo
            return sectionInfo.numberOfObjects
        } else { // collapsed
            return 0
        }
    }

在节标题中定义按钮(我必须将toggleSelection参数_:替换为sender:,以使其对我有用:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if (self.fetchedResultsController.sections!.count > 0) {
        let sectionInfo = self.fetchedResultsController.sections![section]
        let sectionHeaderButton = UIButton(type: .custom)
        sectionHeaderButton.backgroundColor = UIColor.red
        sectionHeaderButton.setTitle(sectionInfo.name, for: [])
        sectionHeaderButton.addTarget(self, action: #selector(MasterViewController.toggleSection(sender:)), for: .touchUpInside)
        return sectionHeaderButton
    } else {
        return nil
    }
}

toggleSection功能:

@objc func toggleSection(sender: UIButton) {
        for (index, frcSection) in self.fetchedResultsController.sections!.enumerated() {
            if sender.title(for: []) == frcSection.name {
                sectionExpandedInfo[index] = !sectionExpandedInfo[index]
                self.tableView.reloadSections(NSIndexSet(index: index) as IndexSet, with: .automatic)
            }
        }
    }

插入或删除部分:

func controller(controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
    switch type {
    case .insert:
        self.sectionExpandedInfo.insert(true, at: sectionIndex)
        self.tableView.insertSections(NSIndexSet(index: sectionIndex) as IndexSet, with: .fade)
    case .delete:
        self.sectionExpandedInfo.remove(at: sectionIndex)
        self.tableView.deleteSections(NSIndexSet(index: sectionIndex) as IndexSet, with: .fade)
    default:
        return
    }
}

再次对pbasdf表示敬意