CCC
CCC

Reputation: 2242

how do I expand cell in tableview dynamically?

I have only one cell with a button in a tableview. The cell height is defined in

tableView:tableView:heightForRowAtIndexPath:

The cell height is 40;

When I click the button, how do I change the cell height to 80? thanks for any help.

Upvotes: 0

Views: 2196

Answers (3)

Yunus Nedim Mehel
Yunus Nedim Mehel

Reputation: 12369

Define a property and @synthesize it:

@property (retain, nonatomic) NSIndexPath* selectedRowIndex;

Override didSelectRowAtIndexPath and heightForRowAtIndexPath methods:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if(selectedRowIndex && indexPath.row == selectedRowIndex.row) {

        //[_yourTableView deselectRowAtIndexPath:indexPath animated:YES]; If you only want the cell to get bigger
        selectedRowIndex = nil;

    }

    else {  self.selectedRowIndex = [indexPath retain];   }

    [tableView beginUpdates];
    [tableView endUpdates];
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

if (tableView == _yourTableView) {


    if(selectedRowIndex && indexPath.row == selectedRowIndex.row){

        return 80;
    }

    // Cell isn't selected so return single height
    return 40;

}

else return 0;
}

Because of the beginUpdates and endUpdates lines this should animate the cell height.

Upvotes: 3

lakshmen
lakshmen

Reputation: 29064

Here is the documentation for UITableView Delegate. You need to set a delegate and set the function is - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath. Remember the return value is CGFloat, so return 80.0 instead of 80. Hope this helps.. Read more about other delegate functions in the documentation...

Upvotes: 1

NikosM
NikosM

Reputation: 1131

When the button is pressed you should set a variable to a value that indicates it has been pressed, then call reloadData on your tableView. This will make tableView:heightForRowAtIndexPath to be called again.

In tableView:heightForRowAtIndexPath check the variable that tells you if the button has been pressed or not and return 80 if it has been pressed

Upvotes: 0

Related Questions