I have a UITableview in my xcode project.In that Comments are listed.How can i focus on a last cell of my TableView with scrolling animation?
To scroll to the top of our tableview we need to create a new IndexPath . This index path has two arguments, row and section . All we want to do is scroll to the top of the table view, therefore we pass 0 for the row argument and 0 for the section argument. UITableView has the scrollToRow method built in.
A view that presents data using rows in a single column. iOS 2.0+ iPadOS 2.0+ Mac Catalyst 13.1+ tvOS 9.0+
Below method will find the last index of you table view and will focus to that cell with an animation
-(void)goToBottom
{
NSIndexPath *lastIndexPath = [self lastIndexPath];
[<YOUR TABLE VIEW> scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
Code to find the last index of your tableview.
-(NSIndexPath *)lastIndexPath
{
NSInteger lastSectionIndex = MAX(0, [<YOUR TABLE VIEW> numberOfSections] - 1);
NSInteger lastRowIndex = MAX(0, [<YOUR TABLE VIEW> numberOfRowsInSection:lastSectionIndex] - 1);
return [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];
}
Add this code somewhere in your view controller
[self performSelector:@selector(goToBottom) withObject:nil afterDelay:1.0];
Keep in mind that a UITableView inherits from UIScrollView
-(void)scrollToBottom:(id)sender
{
CGSize r = self.tableView.contentSize;
[self.tableView scrollRectToVisible:CGRectMake(0, r.height-10, r.width, 10) animated:YES];
}
execute it like
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(…);
[button addTarget:self action:@selector(scrollToBottom:) forControlEvents:UIControlEventTouchUpInside];
(You dont need to use performSelector:…
)
Another solution would be selecting the last row. The table view will take care of the rest.
-(void)scrollToBottom:(id)sender
{
NSInteger lasSection = [self.tableView numberOfSections] - 1;
NSInteger lastRow = [self.tableView numberOfRowsInSection:lasSection]-1;
//this while loops searches for the last section that has more than 0 rows.
// maybe you dont need this check
while (lastRow < 0 && lasSection > 0) {
--lasSection;
lastRow = [self.tableView numberOfRowsInSection:lasSection]-1;
}
//if there is no section with any row. if your data source is sane,
// this is not needed.
if (lasSection < 0 && lastRow < 0)
return;
NSIndexPath *lastRowIndexPath =[NSIndexPath indexPathForRow:lastRow inSection:lasSection];
[self.tableView selectRowAtIndexPath:lastRowIndexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];
}
the button is the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With