UITableViewCell 展开和折叠 [英] UITableViewCell expand and collapse
问题描述
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//case 1
//The user is selecting the cell which is currently expanded
//we want to minimize it back
if(selectedIndex == indexPath.row)
{
selectedIndex = -1;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
return;
}
//case 2
//First we check if a cell is already expanded.
//If it is we want to minimize make sure it is reloaded to minimize it back
if(selectedIndex >= 0)
{
NSIndexPath *previousPath = [NSIndexPath indexPathForRow:selectedIndex inSection:0];
selectedIndex = indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:previousPath] withRowAnimation:UITableViewRowAnimationFade];
}
//case 3
//Finally set the selected index to the new selection and reload it to expand
selectedIndex = indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
注意案例 1 和案例 2 如何关联折叠已经展开的行,而案例 3 是关于展开未展开的行.
Notice how case 1 and case 2 are related collpasing already expanded row where as case 3 is about expanding the unexpanded row.
展开和折叠都使用与 reloadRowsAtIndexPaths 函数相同的函数.
Both the expand and collapse use the same function of reloadRowsAtIndexPaths function.
对我来说,问题是一个切换按钮,当它展开时,再次运行该功能会折叠,而当它折叠时,它会展开??
推荐答案
当你调用 reloadRowsAtIndexPaths:
表视图将通过调用你的 tableView 实现重新加载那些行:cellForRowAtIndexPath:
在你的 UITableViewDataSource
中.您可以在那里返回一个单元格,该单元格使用 selectedIndex
变量来决定它应该显示为展开还是折叠(无论这对您的特定应用程序意味着什么).它还会在您的 UITableViewDelegate
上调用 tableView:heightForRowAtIndexPath:
(是的,这在委托中很愚蠢)所以如果您的单元格高度改变了这个方法也应该返回一个值取决于 selectedIndex
.
What will happen is that when you call reloadRowsAtIndexPaths:
the table view will reload those rows by calling your implementation of tableView:cellForRowAtIndexPath:
in your UITableViewDataSource
. It is up to you to return a cell there which uses the selectedIndex
variable to decide if it should appear expanded or collapsed (whatever that means for your specific application). It will also call tableView:heightForRowAtIndexPath:
on your UITableViewDelegate
(yes, it is silly that this is in the delegate) so if your cell height changes this method too should return a value depending on selectedIndex
.
另外,我建议你只调用一次 reloadRowsAtIndexPaths:
,就像这样:
Also, I would suggest you only call reloadRowsAtIndexPaths:
once, like this:
NSMutableArray* rows = [NSMutableArray arrayWithCapacity:2];
// Case 2
if(selectedIndex >= 0)
{
NSIndexPath* previousPath = [NSIndexPath indexPathForRow:selectedIndex inSection:0];
[rows addObject:previousPath];
}
// Case 3
selectedIndex = indexPath.row;
[rows addObject:indexPath];
[tableView reloadRowsAtIndexPaths:rows withRowAnimation:UITableViewRowAnimationFade];
这篇关于UITableViewCell 展开和折叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!