ios - UITableViewCell 展开和折叠

标签 ios uitableview

-(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 是关于展开未展开的行。

展开和折叠都使用 reloadRowsAtIndexPaths 函数的相同功能。

对我来说,问题是一个切换按钮,当它展开时,再次运行该函数将折叠,当它折叠时,它会展开?

最佳答案

当您调用 reloadRowsAtIndexPaths: 时, TableView 将通过在 UITableViewDataSource< 中调用 tableView:cellForRowAtIndexPath: 的实现来重新加载这些行。/。您可以在其中返回一个单元格,该单元格使用 selectedIndex 变量来决定它是否应该显示为展开或折叠(无论这对您的特定应用程序意味着什么)。它还会在您的 UITableViewDelegate 上调用 tableView:heightForRowAtIndexPath: (是的,这是在委托(delegate)中,这很愚蠢),所以如果您的单元格高度发生变化,此方法也应该返回值取决于 selectedIndex

另外,我建议您只调用 reloadRowsAtIndexPaths: 一次,如下所示:

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];

关于ios - UITableViewCell 展开和折叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10985746/

相关文章:

ios - OpenGL ES 像素艺术 - 缩放

ios - 如何在不使用uitableview reloadData的情况下更新部分标题的颜色

ios - 在 UITableView 中设置多个部分

ios - UITableView 的动画高度

UITableView 中的 iPhone 动态 UIButton

android - Xamarin 按钮边框问题

ios - 如何在导航 Controller iOS 10 中正确覆盖 supportedInterfaceOrientations?

ios - UITableViewCell 中的 UIStepper 在点击时出现问题

ios - swift - UITableViewCells 和 SDWebImage 的问题

ios - iOS 框架的版本控制