Friday, June 7, 2013

UITableView scrollToRowAtIndexPath example in Objective C (iOS).

UITableView scrollToRowAtIndexPath

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]
An index path that identifies a row in the table view by its row index and its section index.
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.
YES if you want to animate the change in position, NO if it should be immediate.

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

UITableView scrollToRowAtIndexPath 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].
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:linePos inSection:chapterPos];

[self.tableView reloadData];

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

UITableView scrollToRowAtIndexPath 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 example article.