摺疊列表在以文字內容爲主的網站上很常見,主要用於對導航連接進行分類,包含一個分段列表,每個分段下有一些子選項,可以展開各個子項,也可以關閉,現在來設計一個這樣的列表,首先需要建一個View用來響應點擊事件的(展開列表 關閉列表,在這個過程中表視圖控制器會做兩件事:1更新模型及更新數據 2更新表視圖 可以把點擊的分段保存下來,作爲當前的展開索引 之後可以刷新列表 ,方法有兩種:
1 reloadData ,之後調用insertRowsAtIndexPath:With 和 DeleteRowsAtindexPath:with方法
2 在beginUpdates 和endUpdates之間執行插入或刪除,這裏要注意更新數據的正確性,必須與表視圖匹配,不然會發生崩潰,以下是部分關鍵代碼:
-(void) openAccordionAtIndex:(int) index {
NSMutableArray *indexPaths = [NSMutableArray array];
int sectionCount = [[self.objects objectForKey:[[self.objects allKeys] objectAtIndex:self.currentlyExpandedIndex]] count];
for(int i = 0; i < sectionCount; i ++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:self.currentlyExpandedIndex];
[indexPaths addObject:indexPath];
}
self.currentlyExpandedIndex = -1;
[self.tableView deleteRowsAtIndexPaths:indexPaths
withRowAnimation:UITableViewRowAnimationTop];
self.currentlyExpandedIndex = index;
sectionCount = [[self.objects objectForKey:[[self.objects allKeys] objectAtIndex:self.currentlyExpandedIndex]] count];
[indexPaths removeAllObjects];
for(int i = 0; i < sectionCount; i ++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:self.currentlyExpandedIndex];
[indexPaths addObject:indexPath];
}
double delayInSeconds = 0.35;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self.tableView insertRowsAtIndexPaths:indexPaths
withRowAnimation:UITableViewRowAnimationFade];
});
[self.tableView endUpdates];
}