如何隐藏UITableView中的一项

我最近工作中的一个iOS App中经常有在不同的场合,隐现菜单列表里某一项的需求.
如果初始化的时候就去掉某一项的话,有可能让序号变化, 处理上会比较麻烦容易出错.
我采用了初始化列表相同但是隐藏section的方式,保持序号不变,方便处理.
那么如何隐藏一个section呢?
其实很简单,就是将section的高度设置为0
重载 heightForRowAtIndexPath方法, 假设要隐藏section 1的话,
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.section == 1)
return 0;
else
return 60;
}
简单的列表这样就可以了.
如果你的菜单项带有header和footer, 也需要将他们隐藏, 同理重载heightForHeaderInSection 和 heightForFooterInSection 方法

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
if(section == 1)
return 0.01;
else
return 18;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
if(section == 1)
return 0.01;
else
return 16;
}

注意: 这里没有return 0, 而是return 0.01, 是因为这两个方法不接受0值, 返回0会不起作用. 因为是返回float类型, 所以返回一个较小的数,比如0.01之类的.
另外.如果你派生了viewForFooterInSection 或 viewForHeaderInSection, 隐藏的section要返回nil,否则隐藏不了, 这一点也很重要.
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
if (section == 0) {
return footView0;
} else if (section == 1) {
return nil;
} else if (section == 2) {
return footView2;
} else if (section == 3) {
return footView3
} else if (section == 4)
return footView4;
return nil;
}

viewForHeaderInSection也是同理, 这样就可以隐藏一个section及其header和footer了

原文地址:https://www.cnblogs.com/dqshll/p/5015990.html