实现选择
网上大部分的教程,都是基于修改section的hearderView来实现的,但是看QQ的好友列表,style是grouped,显然不是使用section的header来处理。使用section的hearderView来实现的,十分简单,网上也有很多源码和教程,只要刷新一下dataSource然后调用就可以了。不在本次讨论的范围之内。
1 |
- (void)reloadSections:(NSIndexSet *)sections |
这次我直接使用grouped的cell来做父cell,点击后展开相应的子cell,还有动画特效。(目测QQ好友列表没有使用动画特效,可能是因为好友列表过于大,内存占用问题或者是用户体验问题。)
封装测试数据
使用FMDB(或者CoreData)从objc中国获取主issue作为父级cell,文章作为subCell,具体获取使用python和BeautifulSoup,不在本次的讨论范围之内,需要的可以查看相应的资料或者留言我,也可以在文末的项目源码里获取python代码。
具体实现分析
TableView一些相关方法介绍
delegate里和点击有关的方法如下。
1 2 3 4 |
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath - (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath |
当有点击事件发生时,运行顺序为。
- willSelect
- willDeselect
- didDeselect
- didSelect
插入删除cell的方法为
1 2 |
- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation - (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation |
记得把他们放在
1 2 3 |
[table beginUpdates]; //input insert/delete code here [table endUpdates]; |
逻辑分析
在didSelect的时候执行插入代码。
1 2 3 |
[tableView beginUpdates]; [tableView insertRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationTop]; [tableView endUpdates]; |
1 2 3 |
[tableView beginUpdates]; [tableView deleteRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationRight]; [tableView endUpdates]; |
其中的indexArray需要动态计算。类似这样。
1 2 3 4 5 |
NSMutableArray* indexArray = [NSMutableArray array]; for (int i=1; i<=masterModel.subIuuses.count; i++) { NSIndexPath* path = [NSIndexPath indexPathForRow:i+indexPath.row inSection:indexPath.section]; [indexArray addObject:path]; } |
可以实现这样的效果。
问题分析
看起来没有什么问题。
但是当点击的是展开的cell下方的cell时,indexPath就会出现问题。像下面这样。
我要点击的是2x,但是实际上点击的却是4x,问题出在哪里?看这个图片就会发现问题,原来还是那几个方法的执行顺序问题。
在执行的时候,先执行didDeselect里面的代码,导致插入的cell被删除,indexPath变化,然后再didSelect,当然选中的不是我们想要选中的那个cell了。
解决方案
如下图。
只要willSelect的时候return一个新的indexPath即可,这个indexPath通过计算得出。下面是我的willSelect里的实现代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath]; if (cell & [cell isMemberOfClass:[SIMMasterTableViewCell class]]) { //点击masterCell if (_isShowIssues) { //展开状态 if(indexPath.row>_lastSelectMatserIndexPath.row) return [NSIndexPath indexPathForRow:indexPath.row-_lastModelIssuesCount inSection:indexPath.section]; else return indexPath; } return indexPath; } else if(cell) { _isSelectSubCell = YES; return indexPath; //点击到uitableviewcell } return indexPath; } |
最后放上一张效果图。