iPhone SDK Select Cell in Tableview

24/03/2010

It may be useful to pre-select a cell in a Tableview in an iPhone/iPad app. As part of a persistent restore feature I am adding to an iPad application, I needed just the following code to pre-select the cell.

- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
        self.title = @”Projects”;
        self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
        

        NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:1 inSection:0];
        [tableViewMaster selectRowAtIndexPath:scrollIndexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
        [scrollIndexPath release];
        

}

This worked well for me, as generally when a cell is selected the correct connected code in the application also executes.

To get the correct indexPathforRow: value, I just used NSUserDefaults to store the last selected row. The NSUserDefaults variable is simply updated to the last selected indexPath.row in didSelectRowAtIndexPath

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

//Some Code :)

        [[NSUserDefaults standardUserDefaults] setInteger:indexPath.row forKey:@”LastTouchedContact”];
        [defaults synchronize];
        NSLog(@”Last Touched Client was: %d”,indexPath.row);

}

So now using the NSUserDefault state variable my viewWillAppear is updated to:

- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
        self.title = @”Projects”;
        self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
        
        int lastTouched = [[NSUserDefaults standardUserDefaults] integerForKey:@”LastTouchedContact”];
        
        NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:lastTouched inSection:0];
        [tableViewMaster selectRowAtIndexPath:scrollIndexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
        [scrollIndexPath release];
        

}

No comments yet.

Write a comment:

blog comments powered by Disqus