Search code examples
iosobjective-cuitableviewscrollnsindexpath

Scroll tableView to bottom for last row selection


I have a table view which loads itself on selection of date popover. I want the last tableview cell (which is not visible currently) to be selected and it should scroll to Bottom

I have written the following code

- (void)viewDidLoad {
   [_tableView reloadData];    
[self scrollTableToIndex];
[_tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:_selectedMeetingIndex inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
    [self tableView:_tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:_selectedMeetingIndex inSection:0]];
}
-(void)scrollTableToIndex{

    if(_selectedMeetingIndex <= _arrMeetingsList.count / 2){
        _isTableBottomScrolled = NO;
        [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_selectedMeetingIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }else{
        NSLog(@"_tableView.contentOffset.y %f",_tableView.contentOffset.y);

        if (!_isTableBottomScrolled) {
            _isTableBottomScrolled = YES;
            CGFloat height = self.agendaList.contentSize.height - self.tableView.bounds.size.height;
            [self.tableView setContentOffset:CGPointMake(0, height) animated:YES];

        }
    }
}

The tableview cell is selected but it doesn't scroll to bottom for the first time, however if I select a different date from the date popover, it scrolls to the bottom and the cell is selected.

I have called the function "scrollTableToIndex" in viewDidAppear as well but it doesn't work .

Also if I using this

[self.tableView setContentOffset:CGPointMake(0, CGFLOATMAX) animated:YES];

instead of the below line of code

CGFloat height = self.agendaList.contentSize.height - self.tableView.bounds.size.height;
 [self.tableView setContentOffset:CGPointZero animated:YES];

If i do this then the code works for 1st time but second time, after I select the date from popover, the tableview hangs.

I have referred this link

Please Help.


Solution

  • That's the code I'm using for that:

    - (void) scrollToBottomAnimated:(BOOL) animated
    {
        CGSize contentSize = self.contentSize;
        CGSize boundsSize = self.bounds.size;
        if (contentSize.height > boundsSize.height - self.contentInset.bottom)
        {
            CGPoint bottomOffset = CGPointMake(0, contentSize.height - boundsSize.height + self.contentInset.bottom);
            [self setContentOffset:bottomOffset animated:animated];
        }
    }
    

    I keep this as one of my UITableView category methods, so "self" is just UITableView