I have a tableview that is filled up with dates. My section header is the month name. You can see my tableview over here.
What I want is that it scrolls to the section of the month of that moment. For setting my section headers I use this method.
id <NSFetchedResultsSectionInfo> theSection = [[self.fetchedResultsController sections] objectAtIndex:section];
static NSArray *monthSymbols = nil;
NSArray *dutchMonths = [[NSArray alloc]initWithObjects:@"Januari",@"Februari",@"Maart",@"April",@"Mei",@"Juni",@"Juli",@"Augustus",@"September",@"Oktober",@"November",@"December", nil];
if (!monthSymbols) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setCalendar:[NSCalendar currentCalendar]];
[formatter setMonthSymbols:dutchMonths];
monthSymbols = [formatter monthSymbols];
}
NSLog(@"%@",monthSymbols);
NSInteger numericSection = [[theSection name] integerValue];
NSInteger year = numericSection / 1000;
NSInteger month = numericSection - (year * 1000);
NSString *titleString = [NSString stringWithFormat:@"%@", [monthSymbols objectAtIndex:month-1]];
label.text = titleString;
I know already that I have to use this method.
[sampleListTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
But how do I get the indexpath of the correct row?
Any help? If you need more details. Please help.
Kind regards.
Looks like you can get an index by looping through your sections array (from self.fetchedResultsController) and comparing the month obtained from the object in question to the month from the current date. If you have a match, then your indexPath would be:
You should also make the dutchMonths array static so it isn’t created every time that method is called. Also, if you aren’t using ARC, it’s leaking (unless the release code is not posted). A general rule of thumb is to make the date formatter static too, or manage one instance of it in some way, because it is an expensive operation. I know with this code it is only created once since you only use it to populate the monthSymbols array, but if you need to use the same formatter in other code, then you’ll want to rewrite that.
To do all of this, you should extract the logic in this method and put it in smaller, reusable methods like
Then you can write: