Reputation: 297
Hey everyone I made a UITableView in my app and when a cell is touched it expands the problem I am having is it does not collapse no matter what I have tried, I'm sure its something easy i just cant figure it out the only time it does collapse is when it another cell is tapped.
Here is my code:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
selectedCellIndexPath = indexPath;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
if (selectedCellIndexPath) {
selected = YES;
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(selectedCellIndexPath != nil
&& [selectedCellIndexPath compare:indexPath] == NSOrderedSame)
return 150;
return 44;
}
Upvotes: 1
Views: 547
Reputation: 380
When you call row reload function does it enter the cellForRow delegate function? If it does then you should put some functionality to collapse the rows after checking for selected row.
Upvotes: 0
Reputation: 12780
I have created the collapsing UITableView
https://github.com/floriankrueger/iOS-Examples--UITableView-Combo-Box/zipball/master http://www.codeproject.com/Articles/240435/Reusable-collapsable-table-view-for-iOS
https://developer.apple.com/library/ios/#samplecode/TableViewUpdates/Introduction/Intro.html
it's working great..
Upvotes: 0
Reputation: 4805
In selectedCellIndexPath you are storing pointer of indexPath. It can change when you reload table, means indexPath object of same cell can be different when you select it second time.
It's safer if you store indexPath.section & indexPath.row
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(_section == indexPath.section && _row == indexPath.row)
{
_section = -1;
_row = -1
}
else
{
_section = indexPath.section;
_row = indexPath.row;
}
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
if (selectedCellIndexPath) {//change it as per your requirement
selected = YES;
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(_section == indexPath.section && _row == indexPath.row)
return 150;
return 44;
}
Upvotes: 0
Reputation: 23634
You're never changing selectedCellIndexPath
to nil
, so the current selected row doesn't get changed until a new one is selected. In didSelectRowAtIndexPath
you should change the beginning to the following:
if (selectedCellIndexPath == indexPath)
selectedCellIndexPath = nil;
else
selectedCellIndexPath = indexPath;
Upvotes: 1