0

我有一个充满日期的表格视图。我的部分标题是月份名称。你可以在这里看到我的表格视图。

我想要的是它滚动到那一刻的月份部分。为了设置我的部分标题,我使用这种方法。

 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;

我已经知道我必须使用这种方法。

[sampleListTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];

但是如何获得正确行的索引路径?

有什么帮助吗?如果您需要更多详细信息。请帮忙。

亲切的问候。

4

1 回答 1

0

看起来您可以通过遍历您的sections数组(来自self.fetchedResultsController)并将从相关对象获得的月份与当前日期的月份进行比较来获取索引。如果您有匹配项,那么您的 indexPath 将是:

NSIndexPath *path = [NSIndexath indexPathForRow:0 inSection:foundIndex];

您还应该将 dutchMonths 数组设为静态,这样就不会在每次调用该方法时都创建它。此外,如果您不使用 ARC,它会泄漏(除非未发布发布代码)。一般的经验法则是将日期格式化程序也设为静态,或以某种方式管理它的一个实例,因为这是一项昂贵的操作。我知道这段代码只创建一次,因为您只使用它来填充monthSymbols 数组,但是如果您需要在其他代码中使用相同的格式化程序,那么您需要重写它。

为此,您应该提取此方法中的逻辑并将其放入更小的、可重用的方法中,例如

- (NSInteger)monthFromSection:(id<NSFetchedResultsSectionInfo>)section;

然后你可以写:

NSIndexPath *path = nil;
NSInteger currentMonth = // Calculate month from date returned by [NSDate date]
NSArray *sections = [self.fetchedResultsController sections];
for (int i = 0; i < sections.count; i++)
{
    if (currentMonth = [self monthFromSection:[sections objectAtIndex:i]])
    {
        path = [NSIndexPath indexPathForRow:0 inSection:i];
        break;
    }
}
于 2012-10-30T16:37:02.890 回答