Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - UITableView not scrolling to bottom

I am building a chat app in iOS but I have some problems with the UITableView displaying all the messages. I want the table view to be scrolled to the bottom on load so users can see the latest messages when they open the app.

To do this I added this code in my function refreshing the data:

    NSIndexPath* ipath = [NSIndexPath indexPathForRow: [self.messageOnTimeline numberOfRowsInSection:0]-1 inSection: 0];
    [self.messageOnTimeline scrollToRowAtIndexPath: ipath atScrollPosition: UITableViewScrollPositionTop animated: YES];

This worked fine until I added a header to the tableview. I added the following code and now it doesn't scroll to the bottom when I load the app:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)];
    return view;
}

Does anyone knows why?

Many thanks for your help

like image 901
Spearfisher Avatar asked Sep 09 '13 10:09

Spearfisher


2 Answers

Add this code in you viewDidload :

Swift 5

let indexPath = IndexPath(item: <Row Index>, section: <Section Index>)
tableView.reloadRows(at: [indexPath], with: .automatic)

Objective C

NSIndexPath *myIndexPath = [NSIndexPath indexPathForRow:AddYourLastIndex inSection:0];
[self.tbl_presentation selectRowAtIndexPath:myIndexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];
like image 191
Darshan Kunjadiya Avatar answered Nov 16 '22 11:11

Darshan Kunjadiya


try this code.it will scroll to bottom of tableview

 [self.tableview setContentOffset:CGPointMake(0, self.tableview.contentSize.height-self.tableview.frame.size.height) animated:YES];
like image 21
hema Avatar answered Nov 16 '22 11:11

hema