简体   繁体   中英

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

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];

试试这个代码。它会滚动到 tableview 的底部

 [self.tableview setContentOffset:CGPointMake(0, self.tableview.contentSize.height-self.tableview.frame.size.height) animated:YES];

@Darshan Kunjadiya answer is right. Even we can achieve the same in storyboard.

Select tableView --> from the storyboard control click on 'add Missing constraints'. That will add the constraint to tableView and View.

That helped me to resolve this issue. A screen_shot attached for reference. screen_shot Link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM