ren*_*enx 3 core-data uitableview ios
let frc = NSFetchedResultsController(
fetchRequest: alertsFetchRequest,
managedObjectContext: self.moc,
sectionNameKeyPath: "formattedDateDue",
cacheName: nil)
Run Code Online (Sandbox Code Playgroud)
当我使用NSFetchedResultsController来记录我的记录时,如何展开和折叠表视图中的部分?
我已经看到很多教程解释了扩展和折叠单元格本身,但没有解释使用获取结果控制器生成的部分.
首先,您需要一个数组来跟踪每个部分是展开还是折叠:
var sectionExpandedInfo : [Bool] = []
Run Code Online (Sandbox Code Playgroud)
在获取结果控制器完成其初始化后performFetch,true为每个部分填充此数组(假设您希望默认情况下展开部分):
sectionExpandedInfo = []
for _ in frc.sections! {
sectionExpandedInfo.append(true)
}
Run Code Online (Sandbox Code Playgroud)
numberOfRowsInSection如果部分折叠,修改方法返回零:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if sectionExpandedInfo[section] { // expanded
let sectionInfo = self.frc.sections![section]
return sectionInfo.numberOfObjects
} else { // collapsed
return 0
}
}
Run Code Online (Sandbox Code Playgroud)
要切换是否扩展了某个部分,我使用了一个按钮作为viewForHeaderInSection标题,其中部分名称为标题:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if (self.frc.sections!.count > 0) {
let sectionInfo = self.frc.sections![section]
let sectionHeaderButton = UIButton(type: .Custom)
sectionHeaderButton.backgroundColor = UIColor.redColor()
sectionHeaderButton.setTitle(sectionInfo.name, forState: .Normal)
sectionHeaderButton.addTarget(self, action: #selector(MasterViewController.toggleSection(_:)), forControlEvents: .TouchUpInside)
return sectionHeaderButton
} else {
return nil
}
}
Run Code Online (Sandbox Code Playgroud)
然后在toggleSection方法I中使用标题来确定已经点击了哪个标题按钮,并展开/折叠相应的部分:
func toggleSection(sender: UIButton) {
for (index, frcSection) in self.frc.sections!.enumerate() {
if sender.titleForState(.Normal) == frcSection.name {
sectionExpandedInfo[index] = !sectionExpandedInfo[index]
self.tableView.reloadSections(NSIndexSet(index: index), withRowAnimation: .Automatic)
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您的FRC插入或删除部分,您需要更新sectionExpandedInfo阵列以包含/删除额外部分:
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.sectionExpandedInfo.insert(true, atIndex: sectionIndex)
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.sectionExpandedInfo.removeAtIndex(sectionIndex)
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
Run Code Online (Sandbox Code Playgroud)
同样,这假设您希望默认情况下展开部分.
| 归档时间: |
|
| 查看次数: |
1274 次 |
| 最近记录: |