首先,你需要一個數組來保持跟蹤每個部分是否展開或摺疊:
var sectionExpandedInfo : [Bool] = []
獲取的成果控制器已經完成了它的初始performFetch
後,填充這個數組true
每個部分(假設你想用默認擴展部分):
sectionExpandedInfo = []
for _ in frc.sections! {
sectionExpandedInfo.append(true)
}
修改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
}
}
要切換節是展開還是不行,我用一個按鈕爲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
}
}
,並在toggleSection
方法我再使用標題以確定哪個標題按鈕已經被挖掘,展開/摺疊的相應部分:
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)
}
}
}
如果您的FRC插入或刪除的部分,你需要更新sectionExpandedInfo
t數組o包括/刪除多餘部分:
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
}
}
再次假設您希望部分在默認情況下展開。
@ uday.m你的編輯不是很好。請勿將「Swift:」前綴添加到問題標題中。 –