Hide cells in a UITableView with static cells - and no autolayout crash

前端 未结 9 1710
庸人自扰
庸人自扰 2021-01-01 16:01

I have a table view form created using Static Cells in IB/Storyboard. However, I need to hide some of the cells at runtime depending on certain conditions.

I have fo

9条回答
  •  迷失自我
    2021-01-01 16:25

    I found the best way to do this is to simply handle the numberOfRowsInSection, cellForRowAtIndexPath and heightForRowAtIndexPath to selectively drop certain rows. Here's a 'hardcoded' example for my scenario, you could do something a little smarter to intelligently remove certain cells rather than hard code it like this, but this was easiest for my simple scenario.

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
        if (indexPath.section == 0 && hideStuff) {
            cell = self.cellIWantToShow;
        }
        return cell;
    }
    
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        CGFloat height = [super tableView:tableView heightForRowAtIndexPath:indexPath];
        if (indexPath.section == 0 && hideStuff) {
            height = [super tableView:tableView heightForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
        }
        return height;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        NSInteger count = [super tableView:tableView numberOfRowsInSection:section];
    
        if (section == 0 && hideStuff) {
            count -= hiddenCells.count;
        }
    
        return count;
    }
    

提交回复
热议问题