Reputation: 8783
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
Upvotes: 8
Views: 11008
Reputation: 3329
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];
Upvotes: 7
Reputation: 1059
@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
Upvotes: 0
Reputation: 199
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];
Upvotes: 3