最近在項目中遇到一個小問題,就是用戶點擊table中的一行,將展開該Cell展示一個subTable。整個功能類似於點擊QQ好友的分組,展開顯示該分組下的好友列表。
該事件發生在用戶點擊該Cell的時候,因此需要在下面方法中編寫代碼:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (((UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath]).isExpanded == NO)
{
((UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath]).isExpanded = YES;
NSMutableArray * indexPaths = [[NSMutableArray alloc] init];
for (int i = 1; i <= _subTable.count; i++)
{
NSIndexPath * subIndexPath = [NSIndexPath indexPathForRow:(indexPath.row + i)
inSection:indexPath.section];
[indexPaths addObject:subIndexPath];
}
[_subDataArr addObjectsFromArray:_subTable];
[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:
UITableViewRowAnimationAutomatic];
[tableView endUpdates];
}
else
{
((UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath]).isExpanded = NO;
NSMutableArray * indexPaths = [[NSMutableArray alloc] init];
for (int i = 1; i <= _subDataArr.count; i++)
{
NSIndexPath * subIndexPath = [NSIndexPath indexPathForRow:(indexPath.row + i) inSection:indexPath.section];
[indexPaths addObject:subIndexPath];
}
[_subDataArr removeAllObjects];
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:
UITableViewRowAnimationAutomatic];
[tableView endUpdates];
}
}
註釋一下:
isExpanded是UITableViewCell的屬性,用來判斷當前的Cell是否已經展了。這個屬性是自己添加的。
_subTable是一個全局的數組,裏面存儲了二級列表中的數據。
_subDataArr是table的dataSource源,而且還控制着numberOfRowInSection這個方法的返回值。因此每次添加數據到這裏面時,該section中的row也同樣會發生變化。
該方法來添加二級列表比較簡單,核心思想就是通過對NSIndexPath的操作來動態改變table的Cell數。使用了tableView的兩個方法,一個add方法和一個delete方法。