user2786037
user2786037

Reputation: 505

UITableViewCell expand animation?

I would like to make something like expandable cells. Result I'm trying to achieve is: What I want

Actually I have:

What I have

Here is my code:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    DoctorCell *cell = self.prototypeCell;
    DoctorModel *doctor = [self.fetchController objectAtIndexPath:frcIndexPath];

    // depending on isActive property I add (or do not add) some content.
    [cell cellForDoctor:doctor isActiveCell:[self.activeCellIndexPath isEqual:indexPath]];
    [cell setNeedsUpdateConstraints];
    [cell setNeedsLayout];
    [cell layoutIfNeeded];

    CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    return height + 1;
}

Here is my cell selection method

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSIndexPath *oldIndexPath = self.activeCellIndexPath;
    if ([indexPath isEqual:self.activeCellIndexPath]) {
        self.activeCellIndexPath = nil;
        oldIndexPath = nil;
    } else {
        self.activeCellIndexPath = indexPath;
    }

    [self.doctorTableView beginUpdates];
    [self.doctorTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, oldIndexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
    [self.doctorTableView endUpdates];

    [self.doctorTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

As you can see, my animation looks weird (kind of moving to wrong position, jumps, etc). What I'm doing wrong? Or do I need to pick another approach for expanding cells?

Upvotes: 1

Views: 3440

Answers (1)

Mundi
Mundi

Reputation: 80271

You can use UITableViews animation automation like this:

  1. Call [tableView beginUpdates];
  2. Change the data source.
  3. Insert or delete rows and sections, or reload them
    • This should cause new heights to be calculated, etc.
    • Make sure you use something appropriate for the withRowAnimation parameter of these methods
  4. Call [tableView endUpdates];

Your animation should now perform as expected.

Maybe your problem is that you selected UITableViewRowAnimationNone for the row animation.

Upvotes: 3

Related Questions