2

I am making a chat page, where I scroll on top, I reload the previous message from API. After getting response, reload the table, and the table moves to first cell. But I want it to be stay where it was during loading the messages. Following are the solutions that I tried:

Solution 1: Declared this: NSMutableDictionary *cellHeightsDictionary;

Added this in viewDidLoad:

    self.chatTableView.rowHeight = UITableViewAutomaticDimension;
    cellHeightsDictionary = @{}.mutableCopy;

Then added the below mentioned methods:

// save height
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cellHeightsDictionary setObject:@(cell.frame.size.height) forKey:indexPath];
}


// give exact height value
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSNumber *height = [cellHeightsDictionary objectForKey:indexPath];
    if (height) return height.doubleValue;
    return UITableViewAutomaticDimension;
}

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

And here reloading my tableview:

- (void)reloadAllMessagesHere {
    [UIView performWithoutAnimation:^{
        [self.chatTableView reloadData];
        [self.chatTableView beginUpdates];
        [self.chatTableView endUpdates];
    }];
}

But still the same issue is happening.

Then I thought I should use the bottom contentOffset of the page. So, I used this method to reload the data:

Solution 2: Removed all above codes and used these methods: For TableView Height:

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

and tableview reload

- (void)reloadWithoutMoving {
    CGPoint contentOffsetVal = CGPointMake(0, self.chatTableView.contentSize.height - self.chatTableView.bounds.size.height);
    [self.chatTableView reloadData];
    [self.chatTableView layoutIfNeeded];
    [self.chatTableView setContentOffset:contentOffsetVal];
}

BUT NO LUCK!!

Here check the two images shown below:

Image 1: Here I am loading the tableview.

Image 2: Here I got the response and the data shown in Image 1 move to bottom automatically

enter image description here enter image description here

How can I fix this?

[P.S. Please don't mark this as duplicate as I have tried previous the solutions but couldn't fix it.]

Gautam Shrivastav
  • 1,198
  • 1
  • 9
  • 22

0 Answers0