Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove cell from static UITableView created in Storyboard

This should be easy, but I'm having trouble.

I have a static UITableView with a cell that I would like to remove programmatically if it's not needed.

I have a IBOutlet for it

IBOutlet UITableViewCell * cell15;

And I can remove it by calling

cell15.hidden = true;

This hides it, but leaves a blank space where the cell used to be and I can't get rid of it.

Perhaps a hack would be to change the height of it to 0?

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:indexPath
{
//what would I put here?
}

Thanks so much!

like image 496
dot Avatar asked Apr 25 '12 06:04

dot


People also ask

How do I delete a cell in UITableView?

So, to remove a cell from a table view you first remove it from your data source, then you call deleteRows(at:) on your table view, providing it with an array of index paths that should be zapped. You can create index paths yourself, you just need a section and row number.

How do I deselect a selected UITableView cell?

How to deselect a UITableViewCell using clearsSelectionOnViewWillAppear. If you set this property to be true the user's selected cell will automatically be deselected when they return to the table view.


2 Answers

You can't really deal with this in the datasource since with static tables you don't even implement the datasource methods. The height is the way to go.

Try this:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == cell15 && cell15ShouldBeHidden) //BOOL saying cell should be hidden
        return 0.0;
    else
        return [super tableView:tableView heightForRowAtIndexPath:indexPath]; 
} 

Update

It appears that, under autolayout, this may not be the best solution. There is an alternative answer here which may help.

like image 148
jrturton Avatar answered Nov 02 '22 23:11

jrturton


You can use tableView:willDisplayCell and tableView:heightForRowAtIndexPath with the cell identifier to show/hide static tableview cells, but yo must implement heightForRowAtIndexPath referring to super, not to self. These two methods work fine for me:

(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([cell.reuseIdentifier.description isEqualToString:@"cellCelda1"]) {
    [cell setHidden:YES];
    }
}

and

(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    if ([cell.reuseIdentifier.description isEqualToString:@"cellCelda1"]) {
        return 0;
}
    return cell.frame.size.height;
}
like image 25
Juan Pablo González Avatar answered Nov 03 '22 00:11

Juan Pablo González