Search code examples
iphonexcodeuitableviewif-statementcell

Xcode - IF statement fails in heightForRowAtIndexPath


This is what I currently have:

In cellForRowAtIndexPath

if ([userSelection  isEqualToString:comparison]){

    changeHeight = NO;

} else if(![userSelection isEqualToString:comparison]) {
    [cell setHidden:YES];
    changeHeight = YES;
}
return cell;

Here is the heightForRowAtIndexPath

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(changeHeight == YES) {
    return 0;
} else return 44;

changeHeight = NO;
}

The if statement is the cellForRowAtIndexPath works perfectly, but the one in the heightForRowAtIndexPath doesn't evaluate and always returns 44 - no matter is the equality in cellForRowAtIndexPath is true or not.

Any ideas?


Solution

  • You are not holding state correctly and are making the assumption that heightForRowAtIndexPath will be called immediately after cellForRowAtIndexPath is called. That might be true, but I would expect the order of calling to be undefined and it might not even be calling with respect to the same cell.

    So you need to keep state on a per-cell basis, rather than a single "changeHeight" flag.

    Now I cannot design all that for you, but you simply need to extend your model data to hold what you want the height of each cell to be.

    Also think about what this statement does (it's not related to your question, but you still need to sort it out):

    if ([userSelection  isEqualToString:comparison]){
    
    } else if(![userSelection isEqualToString:comparison]) {
    
    }