Search code examples
objective-ciosuitableviewcustom-cell

iOS custom cell expandable - index 0 issue


Thanks for the help. I have a custom cell that I expand using the following code. However, the first cell (index 0) always expands upon launch of the ViewControllers?

What am I missing? How do you have them all unExpanded upon launch and expand only upon selection.

Many Thanks.

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        CustomCellCell *cell;
        static NSString *cellID=@"myCustomCell";
        cell = [tableView dequeueReusableCellWithIdentifier:cellID];

        if (cell == nil) 
        {
            NSArray *test = [[NSBundle mainBundle]loadNibNamed:@"myCustomCell" owner:nil options:nil];
            if([test count]>0)
            {
                for(id someObject in test)
                { 
                    if ([someObject isKindOfClass:[CustomCellCell class]]) {
                        cell=someObject;
                        break;
                    }
                }
            }
        }

        cell.LableCell.text = [testArray objectAtIndex:[indexPath row]];
        NSLog( @"data testarray table %@", [testArray objectAtIndex:[indexPath row]]);
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }

    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        self.selectedRow = indexPath.row;
        CustomCellCell *cell = (CustomCellCell *)[tableView cellForRowAtIndexPath:indexPath];

        [tableView beginUpdates];
        [tableView endUpdates];

        cell.buttonCell.hidden = NO;
        cell.textLabel.hidden = NO;
        cell.textfiledCell.hidden = NO;
        cell.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        cell.clipsToBounds = YES;
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        if(selectedRow == indexPath.row) {
            return 175;
        }

        return 44;
    }

Solution

  • That is because default value of selectedRow is zero. You need to initialize it as,

    selectedRow = NSIntegerMax; //or selectedRow = -1;
    

    or some other default value. You can add this in viewDidLoad method or so. Whenever you declare an int type variable, it is default value is zero. So if you have a scenario where zero needs to be checked for example in the above case, you should default it to a value which wont be used at all. Either a negative value or NSIntegerMax can be used for this.