Search code examples
iosuitableviewxamarin.iosxamarinnsindexpath

Scroll UITable to specific table item


So i have a UITableview with 3 different tabs setup.

I want to scroll the table to a specific item.

If user added a new item, table to scroll all the way to the bottom because that's where the item will be added.

If user picks one of the items and edits it, it should come back to the same position on the table. Not scrolled to the top or bottom.

This is what I have:

This is a class variable.
NSIndexpath lastScrollY;

In my ViewWillDisappear :
lastScrollY = this.tableView.IndexPathForSelectedRow() ;

In my ViewWillAppear:
if(lastScrollY != null) {
this.tableView.ScrollToRow(lastScrollY, UITableViewScrollPosition.None, true); }

this does not seem to work. And that is only for when user selects a saved item. What about when then add a new item/row to the table?

Please explain in detail as I am new to this.

Thank you for your time!


Solution

  • For after you add a new cell to your tableView, use the same method you did before, but change the scroll position (this code is in Objective-C, but does the same thing as yours. I'll try to help with a translation if you need one):

    [tableView scrollToRowAtIndexPath:indexPath
                     atScrollPosition:UITableViewScrollPositionBottom 
                             animated:true];
    

    You might also want to set lastScrollY in an override of the method

    (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath
    

    using the automatically passed in value indexPath to save to lastScrollY.

    Lastly, I'm not sure if this will help, but in your current scrollToRow call, you have it scrolling to "none", try having it scroll to UITableViewScrollPositionTop instead. If that still doesn't work, try calling [tableView reloadData] at the end of your viewWillAppear method, which is probably something along the lines of tableView.reloadData() in your language.

    Hope this helps!