Friday, June 7, 2013

UITableView scrollToRowAtIndexPath atScrollPosition animated example in Objective C (iOS).


UITableView scrollToRowAtIndexPath atScrollPosition animated

Scrolls the receiver until a row identified by index path is at a particular location on the screen.

- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated

Parameters of [UITableView scrollToRowAtIndexPath atScrollPosition animated]
indexPath
An index path that identifies a row in the table view by its row index and its section index.
scrollPosition
A constant that identifies a relative position in the receiving table view (top, middle, bottom) for row when scrolling concludes. See “Table View Scroll Position” for descriptions of valid constants.
animated
YES if you want to animate the change in position, NO if it should be immediate.

Discussion of [UITableView scrollToRowAtIndexPath atScrollPosition animated]
Invoking this method does not cause the delegate to receive a scrollViewDidScroll: message, as is normal for programmatically-invoked user interface operations.

UITableView scrollToRowAtIndexPath atScrollPosition animated example.
Calling code

MyViewController *cont = [[MyViewController alloc] initWithMedication:medication];
cont.sectionToShow = 1;
[self.navigationController pushViewController:cont animated:YES];

[cont release];
Viewcontroller code inside viewWillAppear

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:self.sectionToShow];
[cont.tableview scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];

Example of [UITableView scrollToRowAtIndexPath atScrollPosition animated].
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:linePos inSection:chapterPos];

[self.tableView reloadData];

[self.tableView scrollToRowAtIndexPath:indexPath
    atScrollPosition:UITableViewScrollPositionTop animated:YES];

UITableView scrollToRowAtIndexPath atScrollPosition animated example.
- (void)viewDidAppear:(BOOL)animated
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    if ([userDefaults valueForKey:@"content_row"] != nil)
    {
        int rowToHighlight = [[userDefaults valueForKey:@"content_row"] intValue];
        NSIndexPath * ndxPath= [NSIndexPath indexPathForRow:rowToHighlight inSection:0];
        [contentTableView reloadData];
        [contentTableView scrollToRowAtIndexPath:ndxPath atScrollPosition:UITableViewScrollPositionTop  animated:YES];
    }
}

-(void) viewWillDisappear:(BOOL)animated
{
    NSIndexPath *selectedRowPath = [[contentTableView indexPathsForVisibleRows] objectAtIndex:0];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setInteger:selectedRowPath.row forKey:@"content_row"];
}

End of UITableView scrollToRowAtIndexPath atScrollPosition animated example article.